{-|
  Module     : Protocol
  Copyright  : Copyright (C) 2010 https://github.com/berufsnerd
  License    : GPLv3

  Portability: non-portable
  
  Protocol related functions
-}
module Protocol(
  initState
, execQuery
) where

import Prelude hiding (lookup)
import Data.Map

import Types
import Data
import State

-- | The start state
initState = State Unauthicated 0 (Statistics 0)

-- | Execute a query
execQuery 
  :: (Monad m) 
  => State 
  -> Query 
  -> m (State, Reply)

execQuery state Quit 
  = return (state, Okay)

execQuery state (Auth u p) 
  = case auth newstate of 
      Unauthicated    -> return (newstate, Error PermissionError)
      Authenticated _ -> return (newstate, Okay)
      where
        newstate = authUser dic u p state
        dic      = insert "user" "pass" empty

execQuery state (Calc f)
  = case res of
    Left a  -> return (newstate, Error a)
    Right a -> return (newstate, Result a)
    where
      calcResult = calc f state
      res        = snd calcResult
      newstate   = fst calcResult

execQuery state (Unknown) 
  = return (state, Error $ GeneralError "unknown input")
