{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}

module TrelloBoard where

import           Control.Lens         (filtered, preview, (&), (.~), (^..))
import           Data.Aeson
import           Data.Aeson.Lens
import qualified Data.ByteString.Lazy as B
import           Data.Foldable
import           Data.Map             (Map)
import qualified Data.Map             as M
import qualified Data.Text            as T
import           Network.Wreq
import           Observation
import           System.Environment


configOpts :: IO Options
configOpts = do
  env <- getEnvironment
  config <- return $ traverse (\k -> lookup k env) ["TRELLO_KEY", "TRELLO_TOKEN"]
  (key,token) <-
        case config of
          Just [key,token] -> return (T.pack key, T.pack token)
          _ -> fail "couldn't get config"
  return $
      defaults
        & param "key" .~ [key]
        & param "token" .~ [token]


trelloDispatch :: Observation -> IO ()
trelloDispatch (Observation{..}) = do
  opts <- configOpts
  boards <- asJSON =<< getWith (opts & param "filter" .~ ["starred"]
                                     & param "lists" .~ ["open"]
                                     & param "fields" .~ ["name"])
                               "https://api.trello.com/1/members/me/boards" :: IO (Response [Value])

  let listIds :: [T.Text]
      listIds =
        boards ^.. responseBody
            . traverse
              . key "lists"
              . _Array
                . traverse
                  . filtered ((== Just "Observe") . preview (key "name" . _String))
                  . key "id"
                  . _String


  forM_ listIds $ \listId ->
    postWith opts "https://api.trello.com/1/cards"
      (object [ "name" .= description, "desc" .= (maybe "" id link), "idList" .= listId ])
