module Utils.Frontend.Modal
  ( Modal(..)
  , customModal
  , modal
  ) where

import ClassyPrelude.Yesod

import Control.Lens
import Utils.Route

import Settings (widgetFile)


data Modal site = Modal
  { modalTriggerId
  , modalId :: Maybe Text
  , modalTrigger :: Maybe Text {- Dynamic URL -} -> Text {- TriggerId -} -> WidgetT site IO ()
  , modalContent :: Either (SomeRoute site) (WidgetT site IO ())
  }

customModal :: Modal site -> WidgetT site IO ()
customModal Modal{..} = do
  triggerId' <- maybe newIdent return modalTriggerId

  $(widgetFile "widgets/modal/modal")

  route <- traverse toTextUrl $ modalContent ^? _Left
  modalTrigger route triggerId'

-- | Create a link to a modal
modal :: WidgetT site IO () -- ^ Widget that represents the link
      -> Either (SomeRoute site) (WidgetT site IO ()) -- ^ Modal contant: either dynamic link or static widget
      -> WidgetT site IO () -- ^ result widget
modal modalTrigger' modalContent = customModal Modal{..}
  where
    modalTriggerId = Nothing
    modalId = Nothing
    modalTrigger mRoute triggerId = $(widgetFile "widgets/modal/trigger")
