{- DisTract ------------------------------------------------------\
 |                                                                 |
 | Copyright (c) 2007, Matthew Sackman (matthew@wellquite.org)     |
 |                                                                 |
 | DisTract is freely distributable under the terms of a 3-Clause  |
 | BSD-style license. For details, see the DisTract web site:      |
 |   http://distract.wellquite.org/                                |
 |                                                                 |
 \-----------------------------------------------------------------}

module DisTract.IOUtils
    (loadAndUpdateAll,
     loadAll,
     updateAndLoadBug)
    where

import DisTract.Bug
import DisTract.Layout
import DisTract.Parsers
import DisTract.Monotone.Interaction
import DisTract.Types
import Data.List
import Data.Either
import Data.Maybe
import Control.Monad
import System.Directory

loadAndUpdateAll :: Config -> IO [Maybe Bug]
loadAndUpdateAll config
    = loadAllBugIds config >>= mapM (updateAndLoadBug config)

loadAll :: Config -> IO [Maybe Bug]
loadAll config
    = loadAllBugIds config >>= mapM (loadBug config)

loadAllBugIds :: Config -> IO [BugId]
loadAllBugIds config
    = do { baseBranch <- mtnFindCurrentBranch config bugs
         ; branches <- mtnGetBranches config
         ; let bugBranches = filter (isPrefixOf (baseBranch ++ "."))
                             branches
         ; return $ let len = 1 + length baseBranch
                    in map (dieErr . findBugId . drop len)
                       bugBranches
         }

dieErr :: (Show a) => Either a b -> b
dieErr (Left a) = error $ show a
dieErr (Right b) = b

updateAndLoadBug :: Config -> BugId -> IO (Maybe Bug)
updateAndLoadBug config bugId
    = do { exists <- doesDirectoryExist path
         ; if exists
           then mtnUpdate config path Nothing
           else return ()
         ; loadBug config bugId
         }
    where
      path = bugIdToPath config bugId