{-# OPTIONS_GHC -fno-warn-orphans #-}

module Yesod.Form.Fields.Instances
  () where

import ClassyPrelude hiding (foldMap)
import Yesod.Form.Fields

import Data.Foldable (Foldable(..))


deriving instance Foldable Option
deriving instance Traversable Option

instance Foldable OptionList where
  foldMap f OptionList{..} = foldMap (foldMap f) olOptions
  foldMap f OptionListGrouped{..} = foldMap (foldMap (foldMap f) . snd) olOptionsGrouped


instance Semigroup (OptionList a) where
  a@OptionList{} <> b@OptionList{} = OptionList
    { olOptions      = olOptions a <> olOptions b
    , olReadExternal = \inp -> olReadExternal a inp <|> olReadExternal b inp
    }
  a@OptionListGrouped{} <> b@OptionListGrouped{} = OptionListGrouped
    { olOptionsGrouped      = olOptionsGrouped a <> olOptionsGrouped b
    , olReadExternalGrouped = \inp -> olReadExternalGrouped a inp <|> olReadExternalGrouped b inp
    }

  a@OptionListGrouped{} <> b = OptionList (concatMap snd $ olOptionsGrouped a) (olReadExternalGrouped a) <> b
  a <> b@OptionListGrouped{} = a <> OptionList (concatMap snd $ olOptionsGrouped b) (olReadExternalGrouped b)

instance Monoid (OptionList a) where
  mempty = OptionListGrouped
    { olOptionsGrouped      = mempty
    , olReadExternalGrouped = const Nothing
    }
