{-# LANGUAGE TemplateHaskell #-}
-----------------------------------------------------------------------------
-- |
-- Module     : Gitlab.Wikis
-- Copyright  : (c) Daniel Firth 2018
-- License    : BSD3
-- Maintainer : locallycompact@gmail.com
-- Stability  : experimental
--
-- This file defines the Gitlab API V4 Wikis API
-- (https://docs.gitlab.com/ce/api/wikis.html)
--
-----------------------------------------------------------------------------

module Gitlab.Wikis
  ( -- * Data Types/Lenses
    GitlabWikiPage(..)
  , glWikiPageContent
  , glWikiPageFormat
  , glWikiPageSlug
  , glWikiPageTitle

   -- * API
  , getProjectWiki
  , createWikiPage
  )
where

import           Data.Aeson
import           Gitlab.Core
import           Lens.Micro.Platform     hiding ( (.=) )
import           Network.HTTP.Conduit
import           RIO

data GitlabWikiPage = GitlabWikiPage {
  _glWikiPageContent :: Text
, _glWikiPageFormat  :: Text
, _glWikiPageSlug    :: Text
, _glWikiPageTitle   :: Text
} deriving (Eq, Show)

$(makeLenses ''GitlabWikiPage)

instance FromJSON GitlabWikiPage where
  parseJSON = withObject "GitlabWikiPage" $ \v -> GitlabWikiPage
    <$> v .: "content"
    <*> v .: "format"
    <*> v .: "slug"
    <*> v .: "title"

instance ToJSON GitlabWikiPage where
  toJSON x = object ["content" .= _glWikiPageContent x,
                     "format"  .= _glWikiPageFormat x,
                     "slug"    .= _glWikiPageSlug x,
                     "title"   .= _glWikiPageTitle x]

getProjectWiki :: MonadGitlab env m => Text -> m [GitlabWikiPage]
getProjectWiki p = gitlabRequest
  "GET"
  ("/projects/" <> rParam p <> "/wikis?with_content=1")
  mempty

createWikiPage
  :: MonadGitlab env m => Text -> GitlabWikiPage -> m GitlabWikiPage
createWikiPage p o =
  gitlabRequest "POST" ("/projects/" <> rParam p <> "/wikis")
    $ RequestBodyLBS
    $ encode o
