{-# LANGUAGE OverloadedStrings #-}

module Config (
    Config(..),
    getConfig,
    makeOpenSearch
) where

import Data.Maybe (fromMaybe)
import Data.String (fromString, IsString)
import Data.Text (Text)
import Network.Wai.Handler.Warp (HostPreference)
import System.Environment (lookupEnv)

data Config = Config {
    confPort :: Int,
    confHost :: HostPreference,
    confBaseUrl :: Text,
    confFavicon :: Text,
    confUser :: Text,
    confPwHash :: Text
} deriving (Show, Eq)

getConfig :: IO Config
getConfig = Config
    <$> (read <$> getEnvOr "PORT" "20546")
    <*> getEnvOr "BIND_ADDR" "*6"
    <*> getEnvOr "BASE_URL" "http://localhost:20546"
    <*> getEnvOr "FAVICON_URL" "https://69owo.de/favicon.ico"
    <*> getEnvOr "ADMIN_USER" "bleb"
    <*> getEnvOr "ADMIN_PW_HASH" "" -- prevent login without manual pw
  where getEnvOr :: IsString s => String -> s -> IO s
        getEnvOr q def = fromMaybe def . fmap fromString <$> lookupEnv q

makeOpenSearch :: Config -> Maybe Text -> Text
makeOpenSearch cfg defBang =
       "<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\"\n"
    <> "                       xmlns:moz=\"http://www.mozilla.org/2006/browser/search/\">\n"
    <> "    <ShortName>" <> name <> "</ShortName>\n"
    <> "    <Description>Handles search bangs (mostly) locally.</Description>\n"
    <> "    <InputEncoding>UTF-8</InputEncoding>\n"
    <> "    <Image width=\"16\" height=\"16\" type=\"image/x-icon\">" <> confFavicon cfg <> "</Image>\n"
    <> "    <Url type=\"text/html\" template=\"" <> searchUrl <> "\"/>\n"
    <> "</OpenSearchDescription>\n"

  where (searchUrl, name) = case defBang of
            Nothing -> (confBaseUrl cfg <> "/#{searchTerms}", "FastBangs")
            Just b  -> (confBaseUrl cfg <> "/#" <> b <> "#{searchTerms}", "FastBangs (" <> b <> ")")
