module Handler.Utils.Profile
  ( validDisplayName
  ) where

import Import.NoFoundation

import qualified Data.Text as Text
import qualified Data.MultiSet as MultiSet
import qualified Data.Set as Set

import qualified Data.Char as Char


validDisplayName :: Maybe UserTitle
                 -> UserFirstName
                 -> UserSurname
                 -> UserDisplayName
                 -> Bool
validDisplayName (fmap Text.strip -> mTitle) (Text.strip -> fName) (Text.strip -> sName) (Text.strip -> dName)
  = and [ dNameFrags `MultiSet.isSubsetOf` MultiSet.unions [titleFrags, fNameFrags, sNameFrags]
        , sName `Text.isInfixOf` dName
        , all ((<= 1) . Text.length) . filter (Text.any Char.isSpace) $ Text.groupBy ((==) `on` Char.isSpace) dName
        , dNameLetters `Set.isSubsetOf` Set.unions [titleLetters, fNameLetters, sNameLetters, addLetters]
        ]
  where
    titleFrags = MultiSet.fromList $ maybe [] Text.words mTitle
    fNameFrags = MultiSet.fromList $ Text.words fName
    sNameFrags = MultiSet.fromList $ Text.words sName
    dNameFrags = MultiSet.fromList $ Text.words dName

    titleLetters = Set.fromList $ maybe [] unpack mTitle
    fNameLetters = Set.fromList $ unpack fName
    sNameLetters = Set.fromList $ unpack sName
    dNameLetters = Set.fromList $ unpack dName
    addLetters = Set.fromList [' ']
