Option Explicit

Dim MI, Panel, Tmr
'Const TimerTimeout = 10000

Sub OnStartup

    Set MI = SDB.UI.AddMenuItem(SDB.UI.Menu_View, 1, -3)
    MI.Caption = "Visualisation Panel"
    MI.IconIndex = 65
    MI.ShortCut = "Ctrl+Shift+V"
    MI.Hint = "Show the panel for the embedded visualisation"
    Script.RegisterEvent MI, "OnClick", "MIClick"
    
    
    Set Panel = SDB.UI.NewDockablePersistentPanel("VisualisationEmbedder_Panel")
    If Panel.IsNew Then
        Panel.DockedTo = 2
        Panel.Common.Width = 200
        Panel.Common.Height = 200
    End If
    Panel.Caption = "Embedded Visualisation"
    Set SDB.Objects("VisualisationEmbedder_Panel") = Panel        'Storing the Panel in MM's Objects array is only needed to keep it alive the whole time
    Script.RegisterEvent Panel, "OnClose", "PanelClosed"
    'Script.RegisterEvent Panel.Common, "OnResize", "PanelResized"


	If SDB.IniFile.StringValue("VisualisationEmbedder", "PanelVisible") = "True" Then
        RepositionAndResize(Null)
	    Panel.Common.Visible = True
        MI.Checked = True
        
        'Set Tmr = SDB.CreateTimer(TimerTimeout)
        'Script.RegisterEvent Tmr, "OnTimer", "RepositionAndResize"
	Else
	    Panel.Common.Visible = False
        MI.Checked = False
	End If

End Sub


Sub MIClick(MI) 
    
    MI.Checked = Not MI.Checked
    Panel.Common.Visible = MI.Checked
	SDB.IniFile.StringValue("VisualisationEmbedder", "PanelVisible") = MI.Checked
	
    If MI.Checked Then
        RepositionAndResize(Null)
        
        'Set Tmr = SDB.CreateTimer(TimerTimeout)
        'Script.RegisterEvent Tmr, "OnTimer", "RepositionAndResize"
    Else
        Set Tmr = Nothing
    End If

End Sub


Sub PanelClosed(Panel) 

    MI.Checked = False
    SDB.IniFile.StringValue("VisualisationEmbedder", "PanelVisible") = "False"
    Set Tmr = Nothing

End Sub


Sub PanelResized(Panel)

    Call CreateObject("WScript.Shell").Run("""" & SDB.ApplicationPath & "Scripts\Auto\Visualisation Embedder.exe"" reposition", 0, 0)

End Sub


Sub RepositionAndResize(ML) 

    Dim WShell : Set WShell = CreateObject("WScript.Shell")
    Call WShell.Run("""" & SDB.ApplicationPath & "Scripts\Auto\Visualisation Embedder.exe"" embed", 0, 0)
    Call WShell.Run("""" & SDB.ApplicationPath & "Scripts\Auto\Visualisation Embedder.exe"" reposition", 0, 0)

End Sub
