module Message where

import Data.List
import Net
import User

data Command = NAME | UMSG | CMSG | QUIT | UNKNOWN
             deriving (Eq, Show)

data Message = Message
               { command :: Command
               , params  :: [String]
               , mdata   :: String
               } deriving (Show)

data MHandler = MHandler
                { min_params :: Int
                , req_mdata  :: Bool
                , hfunction  :: (Network -> User -> Message -> IO (Bool, User))
                }

parseMessage :: String -> Maybe Message
{--^ `parseMessage` attempts to parse String data received from
a client into a `Message` record.  On success, the Message is
return in the Maybe monad; when parsing fails, Nothing is returned. --}
parseMessage input
  | null elems = Nothing
  | otherwise = let (cmd, sig) = break ( == '/') (head elems)
                    (pms, trailing) = break (isPrefixOf ":") (tail elems)
                in Just Message { command = parseCommand cmd
                                , params = pms
                                , mdata = safeTail (unwords trailing)
                                }
  where
    elems = words input
    safeTail [] = []
    safeTail xs = tail xs

parseCommand :: String -> Command
parseCommand cmd = case cmd of
  "NAME" -> NAME
  "QUIT" -> QUIT
  "UMSG" -> UMSG
  "CMSG" -> CMSG
  _ -> UNKNOWN
