{-# LANGUAGE OverloadedStrings #-}

module Main where

import Control.Applicative ((<$>),(*>))
import Control.Monad.IO.Class (liftIO)
import Control.Lens
import Bort.Application
import Bort.Types
import Bort.MessageHandler as MH
import Data.Attoparsec.Char8
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.UTF8 as UTF

main :: IO ()
main = do
  let settings = def & port     .~ 6665
                     & host     .~ "chat.freenode.net"
                     & name     .~ "chartbort"
                     & rooms    .~ ["##atnl"]
                     & handlers .~ [ sayHiHandler
                                   , whenWillSenpaiNoticeMeHandler
                                   ]
  runBot settings

echoHandler :: MessageHandler
echoHandler = buildHandler (body >>= reply)

debug :: MessageHandler
debug = liftIO . print

prefixedParserHandler :: Parser a -> (a -> MsgHandler ()) -> MsgHandler ()
prefixedParserHandler p f = do n <- botName
                               let prefixedParser = string n *> skipSpace *> p
                               parserHandler prefixedParser f

sayHiHandler :: MessageHandler
sayHiHandler = buildHandler $ prefixedParserHandler "say hi" hiResponse
  where hiResponse _ = do s <- MH.sender
                          reply . C.concat $ ["Hi, ", s, "!"]

modHandler :: MessageHandler
modHandler = buildHandler $ prefixedParserHandler modParser (uncurry modResponse)
  where modParser = do "mod me"
                       skipSpace
                       n <- read <$> many1 digit
                       skipSpace
                       "by"
                       skipSpace
                       k <- read <$> many1 digit
                       return (n,k)
        modResponse n k = let m = n `mod` k :: Integer
                          in reply (C.pack $ show m)

whenWillSenpaiNoticeMeHandler :: MessageHandler
whenWillSenpaiNoticeMeHandler = buildHandler $ prefixedParserHandler "when will senpai notice me" senpaiResponse
  where senpaiResponse _ = reply $ UTF.fromString "........それはちょっと..."
