{-# LANGUAGE OverloadedStrings #-}
module Wunderlist.API.WTask
    ( WTask (..)
    , getTasks
    , getTask
    , getCompletedTasks
    , createTask
    ) where

import Control.Monad.IO.Class (MonadIO)

import Data.Aeson
import Data.ByteString as B
import Data.ByteString.Lazy as BL
import qualified Data.ByteString.Char8 as BC
import Data.Text

import Network.HTTP.Conduit

import Wunderlist.Core

data WTask = WTask { wid :: Int
                   , wcreatedAt :: Text
                   , wcreatedById :: Int
                   , wcompleted :: Bool
                   , wstarred :: Bool
                   , wlistId :: Int
                   , wrevision :: Int
                   , wtitle :: Text
                   , wtype :: Text
                   }
             deriving (Show)

instance FromJSON WTask where
        parseJSON (Object v) = WTask <$>
                               v .: "id" <*>
                               v .: "created_at" <*>
                               v .: "created_by_id" <*>
                               v .: "completed" <*>
                               v .: "starred" <*>
                               v .: "list_id" <*>
                               v .: "revision" <*>
                               v .: "title" <*>
                               v .: "type"

-- JSON object for the POST /tasks request body. Not exposed.
data WTaskPostData = TPD { listId :: Int
                         , title :: Text
                         }

instance ToJSON WTaskPostData where
    toJSON (TPD id t) = object ["list_id" .= id, "title" .= t]

-- Fetches all tasks for a given list ID
getTasks :: (MonadIO m) => Int -> WunderlistT m (Maybe [WTask])
getTasks id = getObject "/tasks" [("list_id", Just $ BC.pack $ show id)]

-- Fetches a specific task by ID
getTask :: (MonadIO m) => Int -> WunderlistT m (Maybe WTask)
getTask id = getObject ("/tasks/" `B.append` (BC.pack $ show id)) []

-- Fetches all completed tasks for a given list ID
getCompletedTasks :: (MonadIO m) => Int -> WunderlistT m (Maybe [WTask])
getCompletedTasks id = getObject "/tasks"
                           [ ("list_id", Just $ BC.pack $ show id)
                           , ("completed", Just "true") ]

-- Create a task with the given title, in the list with the given list ID
createTask :: (MonadIO m) => Int -> Text -> WunderlistT m (Maybe WTask)
createTask id t = postObject "/tasks" (TPD id t)
