VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "API_Config"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
' ================ Работа конфигурациями =============
' Shared module version: 20220727
' Tested in: TestCommons
' Depends on: API_JSON
' Required reference: Scripting, API_JSON
Option Explicit

Private Const JSON_IDENT_SIZE_SPACES = 4

Private data_ As Scripting.Dictionary

Private Sub Class_Initialize()
  Call Clear
End Sub

Public Function Contains(sKey$) As Boolean
  Contains = data_.Exists(sKey)
End Function

Public Function GetValue(sKey$, Optional iDefault As Variant = vbNullString) As Variant
  If Not Contains(sKey) Then _
    GoTo RETURN_DEFAULT
    
  If VBA.VarType(data_(sKey)) = vbObject Then
    Set GetValue = data_(sKey)
    Exit Function
  Else
    GetValue = data_(sKey)
    If GetValue <> "" Then _
      Exit Function
  End If
  
RETURN_DEFAULT:
  If VBA.VarType(iDefault) = vbObject Then
    Set GetValue = iDefault
  Else
    GetValue = iDefault
  End If
End Function

Public Function SetValue(sKey$, newVal As Variant)
  If VBA.VarType(newVal) = vbObject Then
    Set data_.Item(sKey) = newVal
  Else
    data_.Item(sKey) = newVal
  End If
End Function

Public Function RemoveKey(sKey$)
  If data_.Exists(sKey) Then _
    Call data_.Remove(sKey)
End Function

Public Function Clear()
  Set data_ = New Scripting.Dictionary
End Function

' Scan configuration from JSON file
' Requires: sFile - path to valid UTF-8 JSON file
Public Function LoadFromFile(sFile$) As Boolean
  Dim iParser As New API_JSON
  Dim newData As Object: Set newData = iParser.LoadFromFile(sFile)
  LoadFromFile = Not newData Is Nothing
  If LoadFromFile Then _
    Set data_ = newData
End Function

' Scan configuration from JSON string
Public Function LoadFromJSON(sJson$) As Boolean
  LoadFromJSON = False
  
  Dim iParser As New API_JSON
  On Error GoTo RETURN_FALSE
  Set data_ = iParser.Parse(sJson)
  
  LoadFromJSON = True
  
RETURN_FALSE:
  On Error GoTo 0
End Function

Public Function SaveToFile(sFile$, Optional bMultiline As Boolean = True) As Boolean
  Dim iParser As New API_JSON
  If bMultiline Then _
    Call iParser.SetupMultiline(JSON_IDENT_SIZE_SPACES)
  SaveToFile = iParser.SaveToFile(sFile, data_)
End Function

Public Function SaveToJSON(Optional bMultiline As Boolean = False) As String
  Dim iParser As New API_JSON
  If bMultiline Then _
    Call iParser.SetupMultiline(JSON_IDENT_SIZE_SPACES)
  SaveToJSON = iParser.CreateJSON(data_)
End Function
