module Dingo.Server
       ( -- Settings:
         DingoSettings
       , defaultDingoSettings
       , dsPort
       , dsResourceBundles
         -- Functions:
       , runApplication
       ) where

import Data.Text (Text)
import Dingo.Internal.Application (Application)
import Dingo.Internal.Callback (CallbackM)
import Dingo.Internal.Server.State (emptyServerState)
import Dingo.Internal.Server.Wai (mkWaiApplication)
import Dingo.ResourceBundle (ResourceBundle)
import Network.Wai.Handler.Warp (runSettings, defaultSettings, Settings(..))

-- | Settings for the Dingo application. This is kept
-- as an abstract type to avoid breaking applications
-- when fields are added. You should use record syntax
-- to change the defaults, e.g.
--
-- > defaultDingoSettings { dsPort = 4900 }
data DingoSettings =
  DingoSettings { dsPort :: Int -- ^ Port to listen on. Default value: 3000
                , dsResourceBundles :: [ResourceBundle] -- ^ Starting resource bundles. Default value: []
                }

-- | Default settings for the Dingo application.
defaultDingoSettings :: DingoSettings
defaultDingoSettings = DingoSettings 3000 []

-- | Run the application with the given settings.
runApplication :: DingoSettings -> Text -> (Application -> CallbackM ()) ->IO ()
runApplication dingoSettings applicationTitle application = do
  serverState <- emptyServerState application applicationTitle $ dsResourceBundles dingoSettings
  runSettings settings $ mkWaiApplication serverState
  where
    settings =
      defaultSettings { settingsTimeout = 60
                      , settingsPort = dsPort dingoSettings
                      }