{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- : dep docopt
module Biz.Cli
  ( Plan (..),
    main,
    Docopt.Docopt (..),
    Docopt.Arguments,
    Docopt.argument,
    Docopt.docopt,
    Docopt.getAllArgs,
    Docopt.getArg,
    Docopt.longOption,
    Docopt.command,
    has,
  )
where

import Alpha
import qualified Data.Text as Text
import qualified System.Console.Docopt as Docopt
import qualified System.Environment as Environment
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.Runners as Tasty

data Plan = Plan
  { help :: Docopt.Docopt,
    move :: Docopt.Arguments -> IO (),
    test :: Tasty.TestTree
  }

main :: Plan -> IO ()
main Plan {..} =
  Environment.getArgs
    +> Docopt.parseArgsOrExit help
    +> \args ->
      if args `has` Docopt.command "test"
        then runTests test
        else
          if args `has` Docopt.longOption "help"
            then Docopt.exitWithUsage help
            else move args

runTests :: Tasty.TestTree -> IO ()
runTests tree = do
  Tasty.installSignalHandlers
  case Tasty.tryIngredients Tasty.defaultIngredients mempty tree of
    Nothing -> do
      hPutStrLn stderr <| Text.pack "no ingredients agreed to run"
      exitFailure
    Just act -> act +> \ok -> if ok then exitSuccess else exitFailure

has :: Docopt.Arguments -> Docopt.Option -> Bool
has = Docopt.isPresent