module Handler.Utils.StudyFeatures
  ( parseStudyFeatures
  ) where

import Import.NoFoundation hiding (try, (<|>))

import Text.Parsec
import Text.Parsec.Text


parseStudyFeatures :: UserId -> UTCTime -> Text -> Either Text [StudyFeatures]
parseStudyFeatures uId now = first tshow . parse (pStudyFeatures uId now <* eof) ""


pStudyFeatures :: UserId -> UTCTime -> Parser [StudyFeatures]
pStudyFeatures studyFeaturesUser studyFeaturesUpdated = do
  studyFeaturesDegree <- StudyDegreeKey' <$> pKey
  void $ string "$$"

  let
    pStudyFeature = do
      _ <- pKey -- Meaning unknown at this time
      void $ char '!'
      _ <- pKey -- Meaning unknown
      void $ char '!'
      studyFeaturesField <- StudyTermsKey' <$> pKey
      void $ char '!'
      studyFeaturesType <- pType
      void $ char '!'
      studyFeaturesSemester <- decimal
      let studyFeaturesValid = True
      return StudyFeatures{..}

  pStudyFeature `sepBy1` char '#'
  
pKey :: Parser Int
pKey = decimal

pType :: Parser StudyFieldType
pType = FieldPrimary   <$ try (string "HF")
    <|> FieldSecondary <$ try (string "NF")

decimal :: Parser Int
decimal = foldl' (\now next -> now * 10 + next) 0 <$> many1 digit'
  where
    digit' = dVal <$> digit
    dVal c = fromEnum c - fromEnum '0'
