import clr
clr.AddReference('Soti.Connect.SemanticEngine.Conversions')
from System.Collections.Generic import List

from Soti.Connect.SemanticEngine.Conversions.Interpreters import FirmwareInterpreter
from Soti.Connect.SemanticEngine.Conversions.Interpreters import FirmwareMetadata
import re

print("Loading SimulatorFirmwareInterpreter")

class SimulatorFirmwareInterpreter(FirmwareInterpreter):

    def GetMetadata(self, fileName, fileBytes):
        #models
        models = List[str]()
        version = ""
        headers = {}

        # Decode the bytearray to an ASCII string
        fileString = bytes(fileBytes).decode('utf-8', errors='ignore')


        lines = fileString.splitlines()
        for line in lines:
            current_section = ""
            line = line.strip()
            if not line:
                continue  # Skip empty lines
            
            # Detect section headers
            if line.startswith('[') and line.endswith(']'):
                current_section = line[1:-1]
            elif current_section == 'Header':
                # Parse key=value lines within the Header section
                match = re.match(r'(\w+)=(.*)', line)
                if match:
                    key, value = match.groups()
                    headers[key] = value

            # Join hex data lines and convert to bytes
        if(headers.get("Type") == "Simulator"):
            models.Add("SOTI@@MQTT-Mobile-Label-Printer@@1")
        version = headers.get("Version")

        return FirmwareMetadata(version, models)
        
    def ValidateVersion(self, rawVersion):
        try:
            float(rawVersion)
            return True
        except ValueError:
            return False
    
    ##version 1 is device state property
    ##version 2 is firmware file version
    def CompareVersions(self, deviceStateVersionRaw, firmwareFileVersionRaw):
        deviceStateVersion = 0.0
        firmwareFileVersion = 0.0
        try:
            deviceStateVersion = float(deviceStateVersionRaw)
            firmwareFileVersion = float(firmwareFileVersionRaw)
        except ValueError:
            raise

        if deviceStateVersion == firmwareFileVersion:
             return 0
        elif deviceStateVersion > firmwareFileVersion:
             return 1
        else:
             return -1

plugin = SimulatorFirmwareInterpreter("SimulatorFirmwareInterpreter")

store.Add(plugin)