module Utils.SystemMessage where

import Import.NoFoundation

import qualified Data.List.NonEmpty as NonEmpty
import Data.List (findIndex)

import Control.Monad.Trans.Maybe (MaybeT(..))


getSystemMessage :: MonadHandler m
                 => NonEmpty Lang -- ^ `appLanguages`
                 -> SystemMessageId
                 -> ReaderT SqlBackend m (Maybe (SystemMessage, Maybe SystemMessageTranslation))
getSystemMessage appLanguages smId = runMaybeT $ do
  SystemMessage{..} <- MaybeT $ get smId
  translations <- lift $ selectList [SystemMessageTranslationMessage ==. smId] []
  let
    avL = NonEmpty.sortWith (\l -> NTop $ findIndex (langMatches l) $ NonEmpty.toList appLanguages) $ systemMessageDefaultLanguage :| map (systemMessageTranslationLanguage . entityVal) translations
  lang <- selectLanguage avL
  return (SystemMessage{..}, find (langMatches lang . systemMessageTranslationLanguage) $ map entityVal translations)
