{-# LANGUAGE OverloadedStrings #-}

module Model.Message.Parts
  ( replaceParts
  , getParts
  ) where

import Data.Maybe (listToMaybe, fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T

import Text.ParserCombinators.Parsec

import Model.Json.MessagePart

replaceParts :: [Text] -> Text -> Text
replaceParts values message =
  T.concat . map (replacePart values) $ getParts message

replacePart :: [Text] -> MessagePart -> Text
replacePart _ (Str str) = str
replacePart values (Order n) =
  fromMaybe (T.concat ["{", T.pack (show n), "}"]) . listToMaybe . drop (n - 1) $ values

getParts :: Text -> [MessagePart]
getParts str =
  case parse partsParser "" (T.unpack str) of
    Right parts -> parts
    Left _ -> []

partsParser :: Parser [MessagePart]
partsParser = many partParser

partParser :: Parser MessagePart
partParser =
  (do _ <- string "{"; n <- read <$> many1 digit; _ <- string "}"; return (Order n))
  <|> (do str <- T.pack <$> many1 (noneOf "{"); return (Str str))