{-|
Module      : Gargantext.Core.Text.List.Social.Find
Description :
Copyright   : (c) CNRS, 2018-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX
-}

module Gargantext.Core.Text.List.Social.Find
  where

-- findList imports
import Control.Lens (view)

import Gargantext.Core (toDBid)
import Gargantext.Core.Types.Individu
import Gargantext.Database.Admin.Config ()
import Gargantext.Database.Admin.Types.Node
import Gargantext.Database.Prelude
import Gargantext.Database.Query.Table.Node.Error
import Gargantext.Database.Query.Tree
import Gargantext.Database.Query.Tree.Root (getRootId)
import Gargantext.Prelude
import Gargantext.Database.Query.Table.Node
import Gargantext.Database.Schema.Node

------------------------------------------------------------------------
findListsId :: (HasNodeError err, HasTreeError err)
            => User -> NodeMode -> DBQuery err x [NodeId]
findListsId u mode = do
  rootId <- getRootId u
  userNode <- getNode rootId
  ns <- map (view dt_nodeId) <$> filter ((== toDBid NodeList) . (view dt_typeId))
                             <$> findNodes' (_node_user_id userNode) rootId mode
  pure ns



-- | TODO not clear enough:
-- | Shared is for Shared with me but I am not the owner of it
-- | Private is for all Lists I have created
findNodes' :: (HasTreeError err, HasNodeError err)
          => UserId
          -> RootId
          -> NodeMode
          -> DBQuery err x [DbTreeNode]
findNodes' loggedInUserId r Private = do
  pv <- (findNodes loggedInUserId r Private $ [NodeFolderPrivate]          <> commonNodes)
  sh <- (findNodes' loggedInUserId r Shared)
  pure $ pv <> sh
findNodes' loggedInUserId r Shared       = findNodes loggedInUserId r Shared  $ [NodeFolderShared, NodeTeam] <> commonNodes
findNodes' loggedInUserId r SharedDirect = findNodes loggedInUserId r Shared  $ [NodeFolderShared, NodeTeam] <> commonNodes
findNodes' loggedInUserId r Public       = findNodes loggedInUserId r Public  $ [NodeFolderPublic ]          <> commonNodes
findNodes' loggedInUserId r PublicDirect = findNodes loggedInUserId r Public  $ [NodeFolderPublic ]          <> commonNodes
findNodes' _loggedInUserId _ Published    = pure [] -- FIXME(adn) What's the right behaviour here?

commonNodes:: [NodeType]
commonNodes = [NodeFolder, NodeCorpus, NodeList, NodeFolderShared, NodeTeam]


