Module Login
	EnableExplicit
	
	;- Private constants
	#Window_Width  = 400
	#Window_Height = 165
	
	;- Private variables
	Global Window
	Global UsernameLabel, UsernameInput, PasswordLabel, PasswordInput, ConnectButton
	
	;- Private declarations
	Declare Handler_BrowserResize()
	Declare Handler_ConnectButton()
	Declare Handler_Login(Success, Result.s, UserData)
	
	;- Public procedures
	Procedure Open()
		Window = OpenWindow(#PB_Any, 0, 0, #Window_Width, #Window_Height, "", #PB_Window_ScreenCentered | #PB_Window_BorderLess)
		
		UsernameLabel = TextGadget(#PB_Any, 30, 33, 100, 20, "Username: ")
		UsernameInput = StringGadget(#PB_Any, 120, 30, 250, 20, "")
		PasswordLabel = TextGadget(#PB_Any, 30, 73, 100, 20, "Password: ")
		PasswordInput = StringGadget(#PB_Any, 120, 70, 250, 20, "", #PB_String_Password)
		ConnectButton = ButtonGadget(#PB_Any, 30, 110, #Window_Width - 60, 25, "Connect")
		SetActiveGadget(UsernameInput)
		
		BindGadgetEvent(ConnectButton, @Handler_ConnectButton())
		BindEvent(#PB_Event_SizeDesktop, @Handler_BrowserResize())
	EndProcedure
	
	;- Private procedures
	Procedure Handler_BrowserResize()
		Protected _Width  = DesktopWidth(0)
		Protected _Height = DesktopHeight(0)
		ResizeWindow(Window, (_Width - #Window_Width) * 0.5, (_Height - #Window_Height) * 0.5, #PB_Ignore, #PB_Ignore)
	EndProcedure
	
	Procedure Handler_ConnectButton()
		Protected Username.s = GetGadgetText(UsernameInput)
		Protected Password.s = GetGadgetText(PasswordInput)
		
		If Username = "" Or Password = ""
			Notify::Toast("Invalid username or password.", Notify::#Error)
			ProcedureReturn
		EndIf
		
		HTTPRequest(#PB_HTTP_Post, "/api/auth/login", "username=" + URLEncoder(Username, #PB_UTF8) + "&password=" + URLEncoder(Password, #PB_UTF8), @Handler_Login())
	EndProcedure
	
	Procedure Handler_Login(Success, Result.s, UserData)
		Protected Root, OK
		Protected Username.s
		
		If Success
			If ParseJSON(0, Result)
				Root = JSONValue(0)
				OK   = GetJSONBoolean(GetJSONMember(Root, "success"))
				If OK
					Username = GetJSONString(GetJSONMember(Root, "username"))
					UnbindGadgetEvent(ConnectButton, @Handler_ConnectButton())
					UnbindEvent(#PB_Event_SizeDesktop, @Handler_BrowserResize())
					CloseWindow(Window)
					Desktop::Open(Username)
				Else
					Notify::Toast("Invalid username or password.", Notify::#Error)
				EndIf
				FreeJSON(0)
			EndIf
		Else
			Notify::Toast("Connection failed. Try again.", Notify::#Error)
		EndIf
	EndProcedure
	
EndModule

; IDE Options = SpiderBasic 3.20 (Windows - x86)
; CursorPosition = 51
; Folding = h
; iOSAppOrientation = 0
; AndroidAppCode = 0
; AndroidAppOrientation = 0
; EnableXP
; DPIAware
; CompileSourceDirectory