import System.Directory
import Control.Arrow
--https://stackoverflow.com/questions/40297001/split-a-list-at-the-first-occurrence-of-an-element
--splitList
splitAtFirst :: Eq a => a -> [a] -> ([a], [a])
splitAtFirst x = (id *** drop 1) . break (x ==)
convertToTime :: ([Char],[Char]) -> Int
convertToTime (hc,sc) = h*60 + s
    where   h   | 'P' `elem` sc = 12+(read hc :: Int)
                | otherwise     = read hc :: Int
            s = read scI :: Int
            scI = init (init sc)
--convertToTime (h,s) = (read h :: Int)*60 + (read s :: Int)
convertToInt :: String -> Int
convertToInt x = convertToTime (splitAtFirst ':' x)
convertToString :: Int -> String
convertToString x = (show h)++":"++(show s)
    where   h = x `quot` 60
            s = x `rem` 60
dTime :: String -> String -> String
dTime x y = convertToString (convertToInt y - convertToInt x)
wage :: String -> String
wage hs = roundTwo (show $ (read (show (convertToInt (hs++"XX"))) :: Double)*z)
    where z = 8.25/60
roundString :: ([Char],[Char]) -> String
roundString (x,c)   | length c > 2 = roundString (x,init c)
                    | otherwise = x++"."++c
roundTwo :: String -> String
roundTwo x = roundString (splitAtFirst '.' x)
input :: String -> String -> IO ()
input file logF = do
    print "Start Time: "
    st <- getLine
    print "End Time: "
    et <- getLine
    let dT = dTime st et
    let newL = "\n|\t"++st++"\t|\t"++et++"\t|\t"++dT++"\t|\t$"++wage dT
    putStrLn (newL ++ "\n")
    appendFile file newL
    
main = do
let file = "log.txt"
let swap = "log_swp.txt"
logFile <- readFile file
writeFile swap logFile
input swap logFile
removeFile file
renameFile swap file
--test
contents <- readFile file
putStr contents
|   Start Time  |   End Time    |   Total Time  |   Amount Earned