{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE OverloadedStrings #-}
module MBug.Options (options, Options(..), showFolderMH) where
import Control.Applicative ((<**>))
import Data.Semigroup      ((<>))
import Data.Text           (Text)
import MBug.Data.FolderMH  (FolderMH (..), readFolderMH, showFolderMH)
import Options.Applicative.Compat
  ( Parser
  , execParser
  , footer
  , fullDesc
  , header
  , help
  , helper
  , info
  , long
  , maybeReader
  , metavar
  , option
  , short
  , showDefaultWith
  , strArgument
  , value
  )

-- | This datatype represent contains all information, that control
-- operation of program: what information to input, how to process it,
-- where to output it.
data Options = Options {
  -- | MH folder to store bug emails.
  _folder :: FolderMH,
  -- | Query to Debian bug system. Something that can be meaningfully
  -- placed after @https://bugs.debian.org/@ url is expected here.
  _query  :: Text
}

-- | Parse '_folder' field of 'Options' datatype from command line.
folderParser :: Parser FolderMH
folderParser = option (maybeReader readFolderMH) mods
  where
    defaultFolderMH = Absolute "debbugs"
    mods = short 'o'
        <> long "into"
        <> value defaultFolderMH
        <> metavar "+folder"
        <> showDefaultWith showFolderMH
        <> help "MH folder to store bug emails"

-- | Parser '_query' field of 'Options' datatype from command line.
queryParser :: Parser Text
queryParser = strArgument mods
  where
    mods = metavar "QUERY"
        <> help "Query to Debian bug system"

-- | Parser for whole 'Options' datatype, combining smaller parsers
-- for individual fields.
optionsParser :: Parser Options
optionsParser = Options <$> folderParser <*> queryParser

-- | Parse 'Options' datatype from command line.
options :: IO Options
options = execParser $ info (optionsParser <**> helper) mods
  where
    mods = fullDesc
        <> header "Download Debian bugs into MH folder"
        <> footer "Copyright (C) 2018 Dmitry Bogatov <KAction@gnu.org>"