{-|
Module      : Gargantext.Core.Config.NLP
Description :
Copyright   : (c) CNRS, 2017-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX

-}

{-# LANGUAGE TemplateHaskell #-}

module Gargantext.Core.Config.NLP (
  -- * Types
  NLPConfig(..)

  -- * Utility functions
  , readConfig

  -- * Lenses
  , nlp_default
  , nlp_languages

  )
  where

import Data.Ini qualified as Ini
import Data.Map.Strict qualified as Map
import Data.Maybe
import Data.Text qualified as T
import Gargantext.Core.Config (readIniFile', val)
import Gargantext.Prelude
import Gargantext.Prelude.Utils (listToMaybeAll)
import Network.URI (URI)
import Network.URI (parseURI)

data NLPConfig = NLPConfig { _nlp_default   :: URI
                           , _nlp_languages :: (Map.Map T.Text URI) }
  deriving (Generic, Show)

iniSection :: Text
iniSection = "nlp"

readConfig :: FilePath -> IO NLPConfig
readConfig fp = do
  ini <- readIniFile' fp
  let val' = val ini iniSection
  let lang_default_text = "EN" -- Change this value by one of your choice: "All", "FR", or "EN"

  let m_nlp_default = parseURI $ cs $ val' lang_default_text

  let m_nlp_keys = filter (\k -> k `notElem` [lang_default_text]) $ fromRight [] $ Ini.keys iniSection ini
  let m_nlp_other = listToMaybeAll $ (\k -> (,) k <$> (parseURI $ cs $ val' k)) <$> m_nlp_keys

  let mRet = NLPConfig <$> m_nlp_default <*> (Map.fromList <$> m_nlp_other)

  case mRet of
    Nothing -> panicTrace $ T.concat [ "Cannot read config file: _nlp_default = "
                                     , T.pack $ show m_nlp_default
                                     , ", _nlp_other = "
                                     , T.pack $ show m_nlp_other ]
    Just ret -> pure ret

makeLenses ''NLPConfig
