module Client.Serve (clientServe) where

import Data.TicTacToe (Board,
                       doMoveO,
                       doMoveX,
                       emptyBoard,
                       showBoard,
                       winX,
                       winO)
import Network.Socket (SockAddr(..),
                       bindSocket,
                       setSocketOption,
                       socket,
                       SocketOption(..),
                       SocketType(..),
                       Family(..),
                       HostAddress,
                       inet_addr,
                       accept,
                       socketToHandle,
                       listen)
import System.IO      (Handle,
                       hPutStrLn,
                       hGetLine,
                       hSetBuffering,
                       IOMode(..),
                       BufferMode(..))
import Client.Util    (getMove,
                       clientWin,
                       serveWin)

clientServe :: HostAddress -> String -> IO ()
clientServe mainServer client = do
  sock <- socket AF_INET Stream 0
  setSocketOption sock ReuseAddr 1
  host <- inet_addr client
  bindSocket sock (SockAddrInet 5441 host)
  listen sock 2
  (_sock, _ ) <- accept sock
  hdl <- socketToHandle _sock ReadWriteMode
  hSetBuffering hdl NoBuffering
  servePlay hdl emptyBoard

servePlay :: Handle -> Board -> IO ()
servePlay hdl board= do
  hPutStrLn hdl $ "Wait..."
  board1 <- getMove (getLine) (putStrLn) (doMoveX) board
  hPutStrLn hdl $ showBoard board1
  if winX board1
    then serveWin hdl
    else do
    putStrLn "Wait..."
    board2 <- getMove (hGetLine hdl) (hPutStrLn hdl) (doMoveO) board1
    putStrLn $ showBoard board2
    if winO board2
      then clientWin hdl
      else servePlay hdl board2
