{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}

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

module IHaskell.Display.Widgets.String.HTMLMath
  ( -- * The HTMLMath Widget
    HTMLMathWidget
    -- * Constructor
  , mkHTMLMath
  ) where

-- To keep `cabal repl` happy when running from the ihaskell repo
import           Prelude

import           Data.Aeson
import           Data.IORef (newIORef)

import           IHaskell.Display
import           IHaskell.Eval.Widgets
import           IHaskell.IPython.Message.UUID as U

import           IHaskell.Display.Widgets.Types
import           IHaskell.Display.Widgets.Layout.LayoutWidget
import           IHaskell.Display.Widgets.Style.DescriptionStyle

-- | A 'HTMLMathWidget' represents a HTML Math widget from IPython.html.widgets.
type HTMLMathWidget = IPythonWidget 'HTMLMathType

-- | Create a new HTML widget
mkHTMLMath :: IO HTMLMathWidget
mkHTMLMath :: IO HTMLMathWidget
mkHTMLMath = do
  -- Default properties, with a random uuid
  UUID
wid <- IO UUID
U.random
  IPythonWidget 'LayoutType
layout <- IO (IPythonWidget 'LayoutType)
mkLayout
  DescriptionStyle
dstyle <- IO DescriptionStyle
mkDescriptionStyle

  let widgetState :: WidgetState 'HTMLMathType
widgetState = forall (w :: WidgetType).
Rec Attr (WidgetFields w) -> WidgetState w
WidgetState forall a b. (a -> b) -> a -> b
$ FieldType 'ViewName
-> FieldType 'ModelName
-> IPythonWidget 'LayoutType
-> StyleWidget
-> Rec Attr StringClass
defaultStringWidget Text
"HTMLMathView" Text
"HTMLMathModel" IPythonWidget 'LayoutType
layout forall a b. (a -> b) -> a -> b
$ forall (w :: WidgetType).
RecAll Attr (WidgetFields w) ToPairs =>
IPythonWidget w -> StyleWidget
StyleWidget DescriptionStyle
dstyle

  IORef (WidgetState 'HTMLMathType)
stateIO <- forall a. a -> IO (IORef a)
newIORef WidgetState 'HTMLMathType
widgetState

  let widget :: HTMLMathWidget
widget = forall (w :: WidgetType).
UUID -> IORef (WidgetState w) -> IPythonWidget w
IPythonWidget UUID
wid IORef (WidgetState 'HTMLMathType)
stateIO

  -- Open a comm for this widget, and store it in the kernel state
  forall a. IHaskellWidget a => a -> Value -> IO ()
widgetSendOpen HTMLMathWidget
widget forall a b. (a -> b) -> a -> b
$ forall a. ToJSON a => a -> Value
toJSON WidgetState 'HTMLMathType
widgetState

  -- Return the widget
  forall (m :: * -> *) a. Monad m => a -> m a
return HTMLMathWidget
widget

instance IHaskellWidget HTMLMathWidget where
  getCommUUID :: HTMLMathWidget -> UUID
getCommUUID = forall (w :: WidgetType). IPythonWidget w -> UUID
uuid