' Gambas module file

Private Const DB_NAME As String = "gambas3.shapes.db"

Private $hConn As Connection

Public Sub Open()
  
  If $hConn Then Return
  
  $hConn = New Connection
  $hConn.Type = "sqlite"
  $hConn.Host = Settings.DefaultDir
  $hConn.Open
  If Not $hConn.Databases.Exist(DB_NAME) Then $hConn.Databases.Add(DB_NAME, "Shapes")
  $hConn.Close()
  
  $hConn.Name = DB_NAME
  $hConn.Open()
  
End

Public Sub Close()
  
  If Not $hConn Then Return
  $hConn.Close
  $hConn = Null
  
End

Public Sub Add(hImageSelection As CImageSelection) As Boolean
  
  Dim rShape As Result
  Dim sShape As String
  Dim sKey As String
  
  Open()
  
  sShape = hImageSelection.Save(ByRef sKey)
  
  rShape = $hConn.Find("shapes", "skey = &1", sKey)
  If rShape.Available Then Return True
  
  rShape = $hConn.Create("shapes")
  rShape!skey = sKey
  rShape!sshape = sShape
  Try rShape.Update()
  If Error Then FMain.ShowErrorWith(("Cannot add shape."))
  
End

Public Sub Load() As CImageSelection[]
  
  Dim aImageSelection As New CImageSelection[]
  Dim rShape As Result
  Dim aShape As Collection[]
  Dim hImageSelection As CImageSelection
  
  Open()
  
  rShape = $hConn.Find("shapes")
  For Each rShape
    hImageSelection = New CImageSelection
    aShape = JSON.FromString(rShape!sshape)
    hImageSelection.Load(aShape)
    aImageSelection.Add(hImageSelection)
  Next
  
  Return aImageSelection
  
End

Public Sub Remove(hImageSelection As CImageSelection)
  
  Dim sShape As String
  Dim sKey As String
  
  Open()
  
  sShape = hImageSelection.Save(ByRef sKey)
  
  Try $hConn.Delete("shapes", "skey = &1", sKey)
  If Error Then FMain.ShowErrorWith(("Cannot remove shape."))
  
End
