module Handler.Utils.Term
  ( groupHolidays
  ) where

import Import

import qualified Data.Set as Set
import qualified Data.Sequence as Seq

groupHolidays :: ( MonoFoldable mono
                 , Enum (Element mono)
                 , Ord (Element mono)
                 )
              => mono -> [Either (Element mono) (Element mono, Element mono)]
groupHolidays = go Seq.empty . foldMap Set.singleton
  where go (acc Seq.:|> Left   x')       (Set.minView -> Just (x, xs))
          | x <= succ x' = go (acc Seq.:|> Right (x', x)) xs
        go (acc Seq.:|> Right (x', x'')) (Set.minView -> Just (x, xs))
          | x <= succ x'' = go (acc Seq.:|> Right (x', x)) xs
        go  acc                          xs'
          | Just (x, xs) <- Set.minView xs' = go (acc Seq.:|> Left x) xs
          | otherwise                       = toList acc
