; Main Code File

; init stuff

UseSQLiteDatabase()
XIncludeFile "kratomfrm1.pbf"
XIncludeFile "splash.pbf"
XIncludeFile "pocketbase.pb"
Declare updatelist() ; declare forward procedure

Opensplash();xPos,yPos)

; init code

dbfile$ = "kratom.db" ; created and setup with dbbrowser for now 

If OpenDatabase(0, dbfile$, "", "")
    ;Debug "Connected to PureBasic.sqlite"
Else
  MessageRequester("ERROR","I can't open the database kratom.db!",#PB_MessageRequester_Error)
EndIf

Openkrt1()

Procedure btn0click (EventType) 
  ;MessageRequester("INFO", "ADD CLICKED")
  DatabaseUpdate(0,"INSERT into kratom (name, type, weight) Values ('"+Trim(GetGadgetText(String_0))+"', '"+Trim(GetGadgetText(String_1))+"','"+GetGadgetText(String_2)+"');")
  updatelist()
EndProcedure

Procedure updatelist()
  ClearGadgetItems(ListView_0)
  If DatabaseQuery(0, "SELECT * FROM kratom")
  While NextDatabaseRow(0) ; Loop for each records
        AddGadgetItem (ListView_0, -1, "Name " + GetDatabaseString(0,1) + " Type " + GetDatabaseString(0,2))
  Wend
EndIf

EndProcedure

Procedure dellist(EventType)
  ; I might need this
  selecteditem = GetGadgetState(ListView_0)
  selectedname$ = GetGadgetItemText(ListView_0,selecteditem)
  RemoveGadgetItem(ListView_0,GetGadgetState(ListView_0)) ; removes it from view
  fldname$ = StringField(selectedname$,2," ")
  pos1 = FindString(selectedname$,fldname$,1,#PB_String_NoCase)
  pos2 = FindString(selectedname$,"Type",1,#PB_String_NoCase) - 6
  key$ = Mid(selectedname$,pos1,pos2)
  key$ = Trim(key$)
  ;Debug "POSES " + pos1 + " " + pos2
  ;Debug "KEY :" + key$ + ":"
  ;Debug "FLDNAME " + fldname$
  ;Debug 
  DatabaseUpdate(0, "DELETE FROM kratom WHERE name = '"+key$+"';")
  ;Debug DatabaseError()
   
EndProcedure

Procedure burn(EventType)
  ; TODO ADD BLACK MAGIC
    If DatabaseQuery(0, "SELECT * FROM kratom ORDER BY RANDOM() * weight DESC LIMIT 1")
  While NextDatabaseRow(0) ; Loop for each records
                           ;AddGadgetItem (ListView_0, -1, "Name " + GetDatabaseString(0,1) + " Type " + GetDatabaseString(0,2))
    MessageRequester("Burn you should","Today you get to burn "+GetDatabaseString(0,1))
  Wend
EndIf
  
EndProcedure


; window init

updatelist()

;AddGadgetItem (ListView_0, -1, "Item " + Str(a) + " of the Listview")
Delay(2500)
HideWindow(splash,#True)
HideWindow(krt1,#False)

;AddGadgetItem (0, -1, "Item " + Str(a) + " of the Listview")

Repeat
    Event = WaitWindowEvent()
    
    Select EventWindow()
      Case krt1
        krt1_Events(Event) ; This procedure name is always window name followed by '_Events'
        
      ;Case DateWindow
        ;DateWindow_Events(Event)
        
    EndSelect
    
  Until Event = #PB_Event_CloseWindow ; Quit on any window close
; IDE Options = PureBasic 6.12 LTS (Linux - x64)
; CursorPosition = 7
; Folding = -
; EnableXP
; DPIAware
; Executable = win32kratom.exe