{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}

module Options where

import Options.Generic
import Data.Maybe (fromMaybe)

import Type (Config(..), Role(..), defaultConfig)

data TunnelOptions = TunnelOptions
  {
    role :: Maybe Text
  , localHost :: Maybe Text
  , localPort :: Maybe Integer
  , remoteHost :: Text
  , remotePort :: Integer
  , forwardHost :: Maybe Text
  , forwardPort :: Maybe Integer
  , randomnessInBytes :: Maybe Integer
  , timeoutInSeconds :: Maybe Integer
  , mtu :: Maybe Integer
  , debug :: Bool
  }
  deriving (Generic, Show, Eq)

instance ParseRecord TunnelOptions


toConfig :: TunnelOptions -> Config
toConfig o =
  let c = defaultConfig
      _role =
        case role o of
          Just "remote" -> Remote
          Just "local" -> Local
          Just "both" -> Both
          _ -> Local
  in
  Config
    {
      _localHost = fromMaybe (_localHost c) (localHost o)
    , _localPort = fromMaybe (_localPort c) (localPort o)
    , _remoteHost = remoteHost o
    , _remotePort = remotePort o
    , _forwardHost = fromMaybe (_forwardHost c) (forwardHost o)
    , _forwardPort = fromMaybe (_forwardPort c) (forwardPort o)
    , _role = _role
    , _randomnessInBytes = fromMaybe (_randomnessInBytes c) (randomnessInBytes o)
    , _timeoutInSeconds = fromMaybe (_timeoutInSeconds c) (timeoutInSeconds o)
    , _mtu = fromMaybe (_mtu c) (mtu o)
    , _debug = debug o
    }
