module Dingo.Internal.Application
       ( Application
       , mkApplication
       , setApplicationTitle
       ) where

import           Data.Aeson (Value, FromJSON(..), ToJSON(..), Value(..))
import           Data.Text (Text)
import qualified Data.Text as T
import           Data.Typeable (Typeable)
import           Dingo.Internal.Base (zeroWidgetId, Command(..))
import           Dingo.Internal.Callback (CallbackM, addCommand)
import           Dingo.Internal.Widget (Widget(..))
import           Text.Blaze (toHtml)
import           Text.Julius (julius)

-- | Application widget. There is exactly one instance of this widget
-- per client browser.
data Application = Application
                 deriving (Show, Typeable)

-- Empty state.
data ApplicationState = ApplicationState ()
                      deriving (Show, Typeable)

-- Need dummy instance.
instance FromJSON ApplicationState where
  parseJSON _ = return $ ApplicationState ()

-- Need dummy instance.
instance ToJSON ApplicationState where
  toJSON _ = Null

-- Widget instance. We don't really need anything except
-- the widget ID.
instance Widget Application ApplicationState where
  getWidgetId _ = zeroWidgetId -- Pre-rendered with this fixed id.
  renderWidget _ = toHtml T.empty
  encodeClientStateJs _ = [julius| null |]
  decodeClientStateJs _ = [julius| null |]
  showWidget _ _ = "Application"

-- Instance of the application widget.
mkApplication :: Application
mkApplication = Application

-- | Set application title.
setApplicationTitle :: Application -> Text -> CallbackM ()
setApplicationTitle _ title = addCommand $ SetTitle title