module Main where

import System.Console.GetOpt
import System.Environment
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Parse
import Info
import Icon

data Options = Options
    { optVersion :: Bool
    , optHelp :: Bool
    , optDzen :: Bool
    , optIcon :: Bool
    , optFg :: String
    , optBg :: String
    , optFormat :: String
    } deriving Show

defaultOptions = Options
    { optVersion = False
    , optHelp = False
    , optDzen = False
    , optIcon = False
    , optFg = "#999999"
    , optBg = "#666666"
    , optFormat = "music volume temp wifi load time"
    }

options :: [OptDescr (Options -> Options)]
options =
    [ Option ['v'] ["version"]
        (NoArg (\opts -> opts { optVersion = True }))
        "shows program version"
    , Option ['h'] ["help"]
        (NoArg (\opts -> opts { optHelp = True }))
        "displays usage info"
    , Option ['d'] ["dzen"]
        (NoArg (\opts -> opts { optDzen = True }))
        "formats output for dzen2"
    , Option ['i'] ["icons"]
        (NoArg (\opts -> opts { optDzen = True, optIcon = True }))
        "adds icons. implies --dzen"
    , Option ['f'] ["fg"]
        (ReqArg (\f opts -> opts { optFg = f }) "COLOUR")
        "sets the colour of the text"
    , Option ['b'] ["bg"]
        (ReqArg (\b opts -> opts { optBg = b }) "COLOUR")
        "sets the colour of the background"
    , Option ['F'] ["format"]
        (ReqArg (\f opts -> opts { optFormat = f }) "\"FORMAT\"")
        "formats info according to FORMAT"
    ]

header = "Usage: hinfo [OPTIONS]\n"
footer = "\nReport bugs to <kaashif@kaashif.co.uk>"

progOpts :: [String] -> IO Options
progOpts argv =
    case getOpt Permute options argv of
        (o,_,[]) -> return (foldl (flip id) defaultOptions o)
        (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))

handleOpts :: Options -> IO ()
handleOpts opts
    | optVersion opts = putStrLn "hinfo 1.0.0.0"
    | optHelp opts = putStrLn $ (usageInfo header options) ++ footer
    | optDzen opts = (getAllDzenInfo dzenopts $ parse $ optFormat opts) >>= TI.putStrLn
    | otherwise = (getAllInfo $ parse $ optFormat opts) >>= TI.putStrLn
    where dzenopts = DzenOpts { fg = T.pack $ optFg opts
        , bg = T.pack $ optBg opts
        , icons = optIcon opts
        }
main = do
    argv <- getArgs
    opts <- progOpts argv
    ensureConfig
    handleOpts opts
