{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}

{- |
Copyright: (c) 2020 Jens Petersen
SPDX-License-Identifier: GPL-2.0-only
Maintainer: Jens Petersen <petersen@redhat.com>

Copr REST client library
-}

module Web.Fedora.Copr
  (coprChroots,
   fedoraCopr)
where

import Data.Aeson.Types (Object)
#if MIN_VERSION_aeson(2,0,0)
import Data.Aeson.Key (toText)
import qualified Data.Aeson.KeyMap as M
#else
import qualified Data.HashMap.Lazy as M
#endif
import Data.List (sortBy)
import Data.Ord (comparing, Down(Down))
import Data.Text (Text)

import Web.Fedora.Copr.API

-- | Get the list of chroots of a user's copr project
coprChroots :: String -- ^ server
            -> String -- ^ owner
            -> String -- ^ project
            -> IO [Text] -- ^ list of chroots
coprChroots :: [Char] -> [Char] -> [Char] -> IO [Text]
coprChroots [Char]
server [Char]
owner [Char]
project = do
  Object
proj <- [Char] -> [Char] -> [Char] -> IO Object
coprGetProject [Char]
server [Char]
owner [Char]
project
  case Text -> Object -> Maybe Object
forall a. FromJSON a => Text -> Object -> Maybe a
lookupKey Text
"chroot_repos" Object
proj :: Maybe Object of
    Maybe Object
Nothing ->
        case Text -> Object -> Maybe [Char]
forall a. FromJSON a => Text -> Object -> Maybe a
lookupKey Text
"error" Object
proj of
          Just [Char]
err -> [Char] -> IO [Text]
forall a. HasCallStack => [Char] -> a
error [Char]
err
          Maybe [Char]
Nothing -> [Text] -> IO [Text]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []
    Just Object
obj -> [Text] -> IO [Text]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Text] -> IO [Text]) -> [Text] -> IO [Text]
forall a b. (a -> b) -> a -> b
$ ((Text -> Text -> Ordering) -> [Text] -> [Text]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ((Text -> Down Text) -> Text -> Text -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing Text -> Down Text
forall a. a -> Down a
Down) ([Text] -> [Text]) -> (Object -> [Text]) -> Object -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Key -> Text) -> [Key] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Key -> Text
toText ([Key] -> [Text]) -> (Object -> [Key]) -> Object -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Object -> [Key]
forall v. KeyMap v -> [Key]
M.keys) Object
obj
#if !MIN_VERSION_aeson(2,0,0)
      where toText = id
#endif

-- | the host name of the Fedora Copr API server
fedoraCopr :: String
fedoraCopr :: [Char]
fedoraCopr = [Char]
"copr.fedorainfracloud.org"