-- SPDX-FileCopyrightText: 2022-2023 Gregor Kleen <gregor@kleen.consulting>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

module Handler.Info.TH
  ( glossaryTerms
  , orGitRevisionEnv, gitDescribeDate
  ) where

import Import

import Language.Haskell.TH

import qualified Data.Char as Char

import qualified Data.Map.Strict as Map
import qualified Data.Text as Text

import Development.GitRev

import System.Environment (lookupEnv)


glossaryTerms :: FilePath -> Q Exp
glossaryTerms basename = do
  translationsAvailable <- i18nWidgetFilesAvailable' basename
  let terms = Map.mapWithKey (\k _ -> "Msg" <> unPathPiece k) translationsAvailable
  [e|Map.fromList $(listE . map (\(int, msg) -> tupE [litE . stringL $ repack int, [e|SomeMessage $(conE $ mkName msg)|]]) $ Map.toList terms)|]
  where
    unPathPiece :: Text -> String
    unPathPiece = repack . mconcat . map (over _head Char.toUpper) . Text.splitOn "-"

orGitRevisionEnv :: Q Exp -> Q Exp
orGitRevisionEnv cont = maybe cont stringE =<< runIO (lookupEnv "GIT_REVISION")

gitDescribeDate :: Q Exp
gitDescribeDate = [e|$gitDescribe <> " (" <> $gitCommitDate <> ")"|]
