-- {-# LANGUAGE MultiParamTypeClasses #-}
-- {-# LANGUAGE FunctionalDependencies #-}
-- {-# LANGUAGE FlexibleInstances #-}
-- {-# LANGUAGE NoMonomorphismRestriction #-}

module HsBot.Base.State where

import HsBot.Base.Database

import qualified Data.Map as M

import List
import HsBot.IRC.User

data State = State { 
      isReady :: Bool,
      currentSender :: String,
      currentChannel :: String, 
      line :: String, 
      users :: [User]
   } deriving (Show, Read)

makeDefaultState :: State
makeDefaultState = State {
      isReady = False,
      currentSender = "", 
      currentChannel = "",
      line = "", 
      users = []
   }

stateNumUsers :: State -> Int
stateNumUsers state = length $ users state

stateSortedUsers :: State -> [User]
stateSortedUsers state = sort $ users state

stateUpdateUser :: State -> String -> (User -> User) -> State
stateUpdateUser state name update = 
   let updatedUsers = usersUpdate name (users state) update 
    in state { users = updatedUsers } 

stateLoad :: String -> IO State
stateLoad databaseFile = do
   file <- readFile databaseFile
   return ( read file :: State )

stateSave :: String -> State -> IO ()
stateSave databaseFile = writeFile databaseFile . show

stateSaveIO :: String -> IO State -> IO ()
stateSaveIO databaseFile state = do
   state' <- state
   writeFile databaseFile (show state')

