{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}

module Language.Rzk.VSCode.Config (
  ServerConfig(..),
) where

import           Data.Aeson
import           Data.Default.Class (Default, def)

data ServerConfig = ServerConfig
  { ServerConfig -> Bool
formatEnabled          :: Bool
  } deriving Int -> ServerConfig -> ShowS
[ServerConfig] -> ShowS
ServerConfig -> String
(Int -> ServerConfig -> ShowS)
-> (ServerConfig -> String)
-> ([ServerConfig] -> ShowS)
-> Show ServerConfig
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ServerConfig -> ShowS
showsPrec :: Int -> ServerConfig -> ShowS
$cshow :: ServerConfig -> String
show :: ServerConfig -> String
$cshowList :: [ServerConfig] -> ShowS
showList :: [ServerConfig] -> ShowS
Show

instance Default ServerConfig where
  def :: ServerConfig
def = ServerConfig
    { formatEnabled :: Bool
formatEnabled = Bool
True
    }

-- We need to derive the FromJSON instance manually in order to provide defaults
-- for absent fields.
instance FromJSON ServerConfig where
  -- Note: "configSection" in ServerDefinition already filters by the "rzk." prefix
  parseJSON :: Value -> Parser ServerConfig
parseJSON = String
-> (Object -> Parser ServerConfig) -> Value -> Parser ServerConfig
forall a. String -> (Object -> Parser a) -> Value -> Parser a
withObject String
"rzkSettings" ((Object -> Parser ServerConfig) -> Value -> Parser ServerConfig)
-> (Object -> Parser ServerConfig) -> Value -> Parser ServerConfig
forall a b. (a -> b) -> a -> b
$ \Object
rzkSettings -> do
    Object
formatSettings <- Object
rzkSettings Object -> Key -> Parser Object
forall a. FromJSON a => Object -> Key -> Parser a
.: Key
"format" -- TODO: how to make this optional?
    Bool
formatEnabled <- Object
formatSettings Object -> Key -> Parser (Maybe Bool)
forall a. FromJSON a => Object -> Key -> Parser (Maybe a)
.:? Key
"enable" Parser (Maybe Bool) -> Bool -> Parser Bool
forall a. Parser (Maybe a) -> a -> Parser a
.!= ServerConfig -> Bool
formatEnabled ServerConfig
forall a. Default a => a
def
    ServerConfig -> Parser ServerConfig
forall a. a -> Parser a
forall (m :: * -> *) a. Monad m => a -> m a
return ServerConfig { Bool
formatEnabled :: Bool
formatEnabled :: Bool
.. }

instance ToJSON ServerConfig where
  toJSON :: ServerConfig -> Value
toJSON (ServerConfig { Bool
formatEnabled :: ServerConfig -> Bool
formatEnabled :: Bool
.. }) = [Pair] -> Value
object
      [ Key
"format" Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Pair] -> Value
object
          [ Key
"enable" Key -> Bool -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Bool
formatEnabled
          ]
      ]