summaryrefslogtreecommitdiff
path: root/haskell/src/SpaceTraders/APIClient/Systems.hs
blob: eb15b4d456c0b3075e3a30933b9f30b8b6dde5f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}

module SpaceTraders.APIClient.Systems
  ( initSystems
  ) where

import Control.Exception
import Network.HTTP.Simple

import SpaceTraders
import SpaceTraders.APIClient.Client
import SpaceTraders.APIClient.Pagination
import SpaceTraders.Database.Systems
import SpaceTraders.Model.System(System)

initSystems :: SpaceTradersT (APIResponse [System])
initSystems = do
  s <- getSystems
  listSystems' Pagination{limit=20, page=((length s) `div` 20) + 1, total=0}
  where
    listSystems' :: Pagination -> SpaceTradersT (APIResponse [System])
    listSystems' p = do
      resp <- sendPaginated (Just p) $ setRequestPath "/v2/systems"
      case resp of
        Left e -> throw e
        Right (APIMessage r (Just p')) -> do
          addSystems r
          if (limit p' * page p' < total p') then listSystems' (nextPage p')
                                             else Right <$> getSystems
        _ -> undefined