﻿B4J=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=8.8
@EndOfDesignText@
'Class module
Sub Class_Globals
	Private ws As WebSocket 'ignore
	' will hold our page information
	Public page As ABMPage
	' page theme
	Private theme As ABMTheme
	' to access the constants
	Private ABM As ABMaterial 'ignore	
	' name of the page, must be the same as the class name (case sensitive!)
	Public Name As String = "home"  '<-------------------------------------------------------- IMPORTANT
	' will hold the unique browsers window id
	Private ABMPageId As String = ""
	' your own variables	
	
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
	' build the local structure IMPORTANT!
	BuildPage		
End Sub

#Region ABM
Private Sub WebSocket_Connected (WebSocket1 As WebSocket)	
	LogDebug("Connected")
		
	ws = WebSocket1		
	
	ABMPageId = ABM.GetPageID(page, Name,ws)
	
	Dim session As HttpSession = ABM.GetSession(ws, ABMShared.SessionMaxInactiveIntervalSeconds)
	If session.IsNew Then
		session.Invalidate
		ABMShared.NavigateToPage(ws, "", "./")
		Return
	End If
		
	If ABMShared.NeedsAuthorization Then
		If session.GetAttribute2("IsAuthorized", "") = "" Then
			ABMShared.NavigateToPage(ws, ABMPageId, "../")
			Return
		End If
	End If		
	ABM.UpdateFromCache(Me, ABMShared.CachedPages, ABMPageId, ws)		
	If page.ComesFromPageCache Then
    	' when we have a page that is cached it doesn't matter if it comes or not from a new connection we serve the cached version.
		Log("Comes from cache")		
    	page.Refresh		
    	page.FinishedLoading		
	Else
    	If page.WebsocketReconnected Then
			LogDebug("Websocket reconnected")
        	' when we have a client that doesn't have the page in cache and it's websocket reconnected and also it's session is new - basically when the client had internet problems and it's session (and also cache) expired before he reconnected so the user has content in the browser but we don't have any on the server. So we need to reload the page.
        	' when a client that doesn't have the page in cache and it's websocket reconnected but it's session is not new - when the client had internet problems and when he reconnected it's session was valid but he had no cache for this page we need to reload the page as the user browser has content, reconnected but we have no content in cache
        	ABMShared.NavigateToPage (ws, ABMPageId, "./" & page.PageHTMLName)
    	Else
        	' when the client did not reconnected it doesn't matter if the session was new or not because this is the websockets first connection so no dynamic content in the browser ... we are going to serve the dynamic content...
'        	Log("Websocket first connection")
			page.Prepare
			ConnectPage			
    	End If
	End If
	LogDebug(ABMPageId)		
End Sub

Private Sub WebSocket_Disconnected
	LogDebug("Disconnected")
End Sub

Sub Page_ParseEvent(Params As Map)
	Dim eventName As String = Params.Get("eventname")
	Dim eventParams() As String = Regex.Split(",",Params.Get("eventparams"))
	
	'log(eventName)
	
	If eventName = "beforeunload" Then
		Log("preparing for url refresh")
		ABM.RemoveMeFromCache(ABMShared.CachedPages, ABMPageId)
		Return
	End If
	Dim caller As Object = page.GetEventHandler(Me, eventName)
	If caller = Me Then
		If SubExists(Me, eventName) Then
			Params.Remove("eventname")
			Params.Remove("eventparams")
			If eventName = "page_dropped" Then
				page.ProcessDroppedEvent(Params)
			End If
			Select Case Params.Size
				Case 0
					CallSub(Me, eventName)
				Case 1
					CallSub2(Me, eventName, Params.Get(eventParams(0)))
				Case 2
					If Params.get(eventParams(0)) = "abmistable" Then
						Dim PassedTables As List = ABM.ProcessTablesFromTargetName(Params.get(eventParams(1)))
						CallSub2(Me, eventName, PassedTables)
					Else
						CallSub3(Me, eventName, Params.Get(eventParams(0)), Params.Get(eventParams(1)))
					End If
				Case Else
					' cannot be called directly, to many param
					CallSub2(Me, eventName, Params)
			End Select
		End If
	Else
		CallSubDelayed2(caller, "ParseEvent", Params) 'ignore
	End If
End Sub

public Sub BuildTheme()
	' start with the base theme defined in ABMShared
	theme.Initialize("pagetheme")
	theme.AddABMTheme(ABMShared.MyTheme)

	' add your specific page themes
	
End Sub

public Sub BuildPage()
	' initialize the theme
	BuildTheme
	
	' initialize this page using our theme
	page.InitializeWithTheme(Name, "/ws/" & ABMShared.AppName & "/" & Name, False, ABMShared.SessionMaxInactiveIntervalSeconds, theme)
	page.ShowLoader=True
	page.PageHTMLName = "index.html"
	page.PageTitle = "PyScript in ABMaterial"
	page.PageDescription = "PyScript"
	page.PageKeywords = ""
	page.PageSiteMapPriority = ""
	page.PageSiteMapFrequency = ABM.SITEMAP_FREQ_YEARLY
		
	page.ShowConnectedIndicator = True
	page.AddExtraJavaScriptFile("https://pyscript.net/alpha/pyscript.js")
'	page.AddExtraCSSFile("https://pyscript.net/alpha/pyscript.css")
			
	' create the page grid
	page.AddRowsM(4,True,20,0, "").AddCells12MP(1,0,0,0,0,"")	
	
	page.BuildGrid 'IMPORTANT once you loaded the complete grid AND before you start adding components		
End Sub

public Sub ConnectPage()			

	Dim pyscript As ABMLabel
	pyscript.Initialize(page, "pyscript", "",ABM.SIZE_A,False,"")
	pyscript.TextAsRAWHTML = $"
<py-env>
  - paths:
    - ../../pyscript/example.py
</py-env>
	<py-script>
import example
import js
from js import document
from pyodide import create_proxy
from random import randint
 
count = 0
 
def button_click(event):
	global count
	count += 1
	document.getElementById("label2").innerHTML = 'Button Clicked ' + str(count)
	


def button2_click(event):
	n1 = 0
	n2 = 0
	n1 = document.getElementById("number1").value
	n2 = document.getElementById("number2").value
	suma = int(n1) + int(n2)
	#console.log(suma)
	#pyscript.write("result", suma)
	document.getElementById("result").innerHTML = str(suma)

def button3_click(event):
    number = example.add_two_numbers(randint(1,10), randint(20,50))
    console.log(number)
    document.getElementById("res1").innerHTML = str(number)

def btn1():
	# The page is ready, clear the "page loading"
	document.getElementById("label2").innerHTML = ''
 
	# Create a JsProxy for the callback function
	click_proxy = create_proxy(button_click)
 
	# Set the listener to the callback
	e = document.getElementById("btn")
	e.addEventListener("click", click_proxy)

def btn2():
	# The page is ready, clear the "page loading"
	document.getElementById("result").innerHTML = ''
 
	# Create a JsProxy for the callback function
	click_proxy = create_proxy(button2_click)
 
	# Set the listener to the callback
	e = document.getElementById("btn2")
	e.addEventListener("click", click_proxy)
	
def btn3():
	# The page is ready, clear the "page loading"
	document.getElementById("res1").innerHTML = ''
 
	# Create a JsProxy for the callback function
	click_proxy = create_proxy(button3_click)
 
	# Set the listener to the callback
	e = document.getElementById("btn3")
	e.addEventListener("click", click_proxy)


#function for counter
counter = 0
def myFunc(param):
    global counter
    counter += 1
    document.getElementById("counter").innerHTML = "Counter = " + str(counter)

    # Stop the Interval timer at 15
    if counter == 15:
            counter = 0
 
# Create a proxy for the callback
proxy = create_proxy(myFunc)
 
# Start an Interval timer for every 1,000 ms
interval_id = js.setInterval(proxy, 1000, "a parameter");
 
#execute button
btn1()
btn2()
btn3()
 
</py-script>"$
	page.Cell(1,1).AddComponent(pyscript)
	
	Dim label As ABMLabel
'	Log(ABM.SIZE_H1)
	label.Initialize(page, "label","Example PyScript in ABMaterial", ABM.SIZE_H4, True, "")
	page.Cell(2,1).AddComponent(label)
	
	Dim label2 As ABMLabel
	label2.Initialize(page, "label2","", ABM.SIze_h4, False, "")
	page.Cell(2,1).AddComponent(label2) 
	
	
	Dim label3 As ABMLabel
	label3.Initialize(page, "counter","", ABM.SIze_h5, False, "")
	page.Cell(2,1).AddComponent(label3)
	
	
	Dim b As ABMButton
	b.InitializeFlat(page, "btn","","","PY 1","")
	page.Cell(2,1).AddComponent(b)
	
	Dim n1 As ABMInput
	n1.Initialize(page,"number1", ABM.INPUT_NUMBER, "Number 1",False, "")
	n1.Text=2
	Dim n2 As ABMInput
	n2.Initialize(page,"number2", ABM.INPUT_NUMBER, "Number 2",False, "")
	n2.Text=2
	Dim result As ABMLabel
	result.Initialize(page, "result","",ABM.SIZE_H5,False,"")
	
	Dim b2 As ABMButton
	b2.InitializeFlat(page, "btn2","","","PY 2","")
	
	page.Cell(3,1).AddComponent(n1)
	page.Cell(3,1).AddComponent(n2)
	page.Cell(3,1).AddComponent(result)
	page.Cell(3,1).AddComponent(b2)

	Dim res1 As ABMLabel
	res1.Initialize(page, "res1", "",ABM.SIZE_H5,True, "")
	Dim btn3 As ABMButton
	btn3.InitializeFlat(page, "btn3","","","PY 3","")
	page.Cell(4,1).AddComponent(res1)
	page.Cell(4,1).AddComponent(btn3)


	' refresh the page
	page.Refresh

	' Tell the browser we finished loading
	page.FinishedLoading
	' restoring the navigation bar position
	page.RestoreNavigationBarPosition
	

End Sub
#end region



#Region ABMPage
' clicked on the navigation bar
Sub Page_NavigationbarClicked(Action As String, Value As String)
	' saving the navigation bar position
	page.SaveNavigationBarPosition
	If Action = "LogOff" Then
		ABMShared.LogOff(page)
		Return
	End If

	ABMShared.NavigateToPage(ws, ABMPageId, Value)
End Sub

Sub Page_DebugConsole(message As String)
	Log("---> " & message)
End Sub
#end region

