{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}

module Config
  ( getConfig
  , Config(..)
  ) where

import Data.ConfigFile
import Data.Text (Text)
import qualified Data.Text as T

import Control.Monad.Trans.Error (runErrorT)
import Control.Monad.IO.Class (liftIO)
import Control.Monad (join)
import Control.Arrow (left)
import Control.Applicative (liftA2)

data Config = Config
  { hostname :: Text
  , port :: Int
  } deriving (Read, Eq, Show)

getConfig :: FilePath -> IO (Either Text Config)
getConfig filePath =
  left (T.pack . show) <$> (runErrorT $ do
    cp <- join $ liftIO $ readfile emptyCP filePath
    liftA2
      Config
      (T.pack <$> get cp "DEFAULT" "hostname")
      (get cp "DEFAULT" "port")
  )