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

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

module IHaskell.Display.Widgets.Link.Link
  ( -- * The Link Widget
    Link
    -- * Constructor
  , mkLink
    -- * Easier constructor
  , jslink
  ) 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.Common

-- | An 'Link' represents a Link widget from IPython.html.widgets.
type Link = IPythonWidget 'LinkType

-- | Create a new link widget
mkLink :: IO Link
mkLink :: IO Link
mkLink = do
  -- Default properties, with a random uuid
  UUID
wid <- IO UUID
U.random

  let widgetState :: WidgetState 'LinkType
widgetState = forall (w :: WidgetType).
Rec Attr (WidgetFields w) -> WidgetState w
WidgetState forall a b. (a -> b) -> a -> b
$ FieldType 'ModelName -> Rec Attr LinkClass
defaultLinkWidget Text
"LinkModel"

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

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

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

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

-- | An easier constructor that links two widgets
jslink :: WidgetFieldPair -> WidgetFieldPair -> IO Link
jslink :: WidgetFieldPair -> WidgetFieldPair -> IO Link
jslink WidgetFieldPair
wfp1 WidgetFieldPair
wfp2 = do
  Link
link <- IO Link
mkLink
  ()
_ <- forall (f :: Field) (w :: WidgetType).
(f ∈ WidgetFields w, IHaskellWidget (IPythonWidget w),
 ToPairs (Attr f)) =>
IPythonWidget w -> SField f -> FieldType f -> IO ()
setField Link
link forall {a :: Field}. (a ~ 'Source) => SField a
Source WidgetFieldPair
wfp1
  ()
_ <- forall (f :: Field) (w :: WidgetType).
(f ∈ WidgetFields w, IHaskellWidget (IPythonWidget w),
 ToPairs (Attr f)) =>
IPythonWidget w -> SField f -> FieldType f -> IO ()
setField Link
link forall {a :: Field}. (a ~ 'Target) => SField a
Target WidgetFieldPair
wfp2
  forall (m :: * -> *) a. Monad m => a -> m a
return Link
link

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