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

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

module IHaskell.Display.Widgets.Layout.LayoutWidget
  ( -- * The Layout Widget
    Layout
    -- * Create a new Layout
  , mkLayout
  ) 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.Types

-- | A 'Layout' represents a Layout from IPython.html.widgets.
type Layout = IPythonWidget 'LayoutType

-- | Create a new Layout
mkLayout :: IO Layout
mkLayout :: IO Layout
mkLayout = do
  -- Default properties, with a random uuid
  UUID
wid <- IO UUID
U.random

  let layoutState :: WidgetState 'LayoutType
layoutState = forall (w :: WidgetType).
Rec Attr (WidgetFields w) -> WidgetState w
WidgetState Rec Attr LayoutClass
defaultLayoutWidget

  IORef (WidgetState 'LayoutType)
stateIO <- forall a. a -> IO (IORef a)
newIORef WidgetState 'LayoutType
layoutState

  let layout :: Layout
layout = forall (w :: WidgetType).
UUID -> IORef (WidgetState w) -> IPythonWidget w
IPythonWidget UUID
wid IORef (WidgetState 'LayoutType)
stateIO

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

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

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