module Handler.Utils.SchoolLdap
  ( parseLdapSchools
  ) where

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

import Text.Parsec
import Text.Parsec.Text

import qualified Data.CaseInsensitive as CI

import qualified Data.Set as Set


parseLdapSchools :: Text -> Either ParseError (Set (CI Text))
parseLdapSchools = parse pLdapSchools ""

pLdapSchools :: Parser (Set (CI Text))
pLdapSchools = Set.fromList . map CI.mk <$> pSegment `sepBy` char ','

pSegment :: Parser Text
pSegment = do
  let
    fragStart = flip label "fragment start" $ do
      void . choice . map (try . string) $ sortOn Down
        [ "l", "st", "o", "ou", "c", "street", "dc" ]
      void $ char '='

  fragStart
  pack <$> manyTill anyChar (try (lookAhead $ char ',' >> fragStart) <|> eof)

