{-|
Module      : Gargantext.API.Node.Corpus.Types
Description :
Copyright   : (c) CNRS, 2017-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX
-}


module Gargantext.API.Node.Corpus.Types where

import Control.Lens ( (?~) )
import Control.Monad.Fail (fail)
import Data.Aeson ( Value(..), (.:), (.=), withText, object, withObject )
import Data.Aeson.Types ( Parser )
import Data.Swagger
import Data.Text qualified as T
import Gargantext.API.Admin.Orchestrator.Types qualified as Types
import Gargantext.Database.Action.Flow.Types (DataOrigin(..))
import Gargantext.Prelude

type EPOAPIToken = Text
type EPOAPIUser = Text

data Database =
    Empty
  | DB Types.ExternalAPIs
  deriving (Eq, Show, Generic)
instance FromJSON Database where
  parseJSON = withObject "Database" $ \o -> do
    db <- o .: "db" :: Parser Text
    case db of
      "Empty" -> pure Empty
      _       -> do
        eapi <- parseJSON (Object o) :: Parser Types.ExternalAPIs
        pure $ DB eapi
instance ToJSON Database where
  toJSON Empty = object [ "db" .= (show Empty :: Text)]
  toJSON (DB db) = toJSON db
instance ToSchema Database where
  declareNamedSchema = genericDeclareNamedSchemaUnrestricted defaultSchemaOptions


datafield2origin :: Datafield -> DataOrigin
datafield2origin (External Empty)   = InternalOrigin Types.IsTex
datafield2origin (External (DB db)) = ExternalOrigin db
-- -- | This isn't really used
datafield2origin _                  = InternalOrigin Types.IsTex

------------------------------------------------------------------------
data Datafield = Gargantext
               | External Database
               | Web
               | Files
  deriving (Eq, Show, Generic)

instance FromJSON Datafield where
  parseJSON (String "Gargantext") = pure Gargantext
  parseJSON (String "Web") = pure Web
  parseJSON (String "Files") = pure Files
  parseJSON (Object o) = do
    db <- o .: "External"
    pure $ External db
  parseJSON x = withText "Datafield" (\text ->
    fail $ "Cannot match pattern '<db>' for string " <> T.unpack text) x

instance ToJSON Datafield where
  toJSON (External db) = toJSON $ object [ ("External", toJSON db) ]
  toJSON s = toJSON (show s :: Text)

instance ToSchema Datafield where
  declareNamedSchema _ = do
    pure $ NamedSchema (Just "Datafield") $ mempty
      & type_ ?~ SwaggerObject
