import System.Environment
import Data.List


-- main = do
--     args <- getArgs
--     progName <- getProgName
--     putStrLn "The arguments are:"
--     mapM putStrLn args
--     putStrLn "The programe name is"
--     putStrLn progName
-- 

-- runhaskell 3-command-line-arguments.hs first second w00t "multi word args"

import System.Directory
import System.IO

dispatch :: [(String, [String] -> IO())]
dispatch = [ ("add", add)
           , ("view", view)
           , ("remove", remove)
           ]

add :: [String] -> IO()
add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n")

view :: [String] -> IO()
view [fileName] = do
    contents <- readFile fileName
    let todoTasks = lines contents  -- 按行拆为列表
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks
    putStr $ unlines numberedTasks  -- 组装为行

remove :: [String] -> IO()
remove [fileName, numberString] = do
    handle <- openFile fileName ReadMode
    (tempName, tempHandle) <- openTempFile "." "temp"
    contents <- hGetContents handle
    let number = read numberString
        todoTasks = lines contents
        newTodoItems = delete (todoTasks !! number) todoTasks
    hPutStr tempHandle $ unlines newTodoItems
    hClose handle
    hClose tempHandle
    removeFile fileName
    renameFile tempName fileName

main = do
    (command:args) <- getArgs
    -- 使用 pattern matching 将参数列表与 command:args 做匹配 command 匹配第一个元素 args 匹配剩余元素
    let (Just action) = lookup command dispatch
    -- (Just action) 匹配查询结果 (Just add) action 就等于 add
    action args
