module IRC.Network(write
                  ,reader
                  ,newConnection
                  ,closeConn) where

import System.IO (Handle
                 ,hGetLine
                 ,hSetBuffering
                 ,BufferMode(NoBuffering)
                 ,hClose) 

import Network (PortID, HostName, connectTo) 
import Text.Printf (hPrintf)

import IRC.Agent

-- reads from the socket. 
reader :: Agent -> IO String
reader a = 
    case conn a of
      Nothing -> return ""
      Just c -> hGetLine c

-- Writes messages to the socket
write ::  String -> String -> Maybe Handle -> IO ()
write  com param mh = 
    case mh of
      Nothing -> return()
      Just h -> hPrintf h "%s %s\r\n" com param

newConnection :: Agent -> IO Agent
newConnection a = do
    h <- connectTo (hostname a) (portNumber a)
    hSetBuffering h NoBuffering
    return $ a { conn = Just h }

closeConn :: Agent -> IO Agent
closeConn a = do
    case conn a of 
      Nothing -> return a

      Just c -> do
        hClose  c 
        return $ a { conn = Nothing }
