import clr
clr.AddReference('Soti.Connect.SemanticEngine.Conversions')

from Soti.Connect.SemanticEngine.Conversions.Interpreters import FirmwareInterpreter
from Soti.Connect.SemanticEngine.Conversions.Interpreters import FirmwareMetadata
from System.Collections.Generic import List
import re

print("Loading MicroplexFirmwareInterpreter")

class MicroplexFirmwareInterpreter(FirmwareInterpreter):

    def GetMetadata(self, fileName, fileBytes):
        models = List[str]()
        version = ""
        fileString = bytes(fileBytes).decode('utf-8', errors='ignore')
        versionPattern = r'^co2 ## Version:\s+(.*)$'
        modelPattern = r'^co2 ## Use for:\s+(.*)$'

        # Search for the patterns
        version_match = re.search(versionPattern, fileString, re.MULTILINE)
        use_for_match = re.search(modelPattern, fileString, re.MULTILINE)

        if version_match:
            version = version_match.group(1).strip()


        if use_for_match:
            models.AddRange(use_for_match.group(1).strip().split(','))

        
        return FirmwareMetadata(version, models)
        
    def ValidateVersion(self, rawVersion):
        try:
            self.parse_version(rawVersion)
            return True
        except:
            return False
    
    def CompareVersions(self, deviceStateVersionRaw, firmwareFileVersionRaw):
        deviceStateVersion = self.parse_version(deviceStateVersionRaw)
        firmwareFileVersion = self.parse_version(firmwareFileVersionRaw)

        # Compare major version
        if deviceStateVersion[0] > firmwareFileVersion[0]:
            return 1
        elif firmwareFileVersion[0] > deviceStateVersion[0]:
            return -1
        
        # Compare minor version
        if deviceStateVersion[1] > firmwareFileVersion[1]:
            return 1
        elif firmwareFileVersion[1] > deviceStateVersion[1]:
            return -1
        
        # Compare suffix
        if deviceStateVersion[2] > firmwareFileVersion[2]:
            return 1
        elif firmwareFileVersion[2] > deviceStateVersion[2]:
            return -1
        
        return 0

    def parse_version(self, version_str):
        # Extract numeric parts and suffix
        match = re.match(r'(\d+)\.(\d+)([A-Za-z]*)', version_str)
        if match:
            major = int(match.group(1))
            minor = int(match.group(2))
            suffix = match.group(3)
            return (major, minor, suffix)
        else:
            raise ValueError("Invalid version format")
        

plugin = MicroplexFirmwareInterpreter("MicroplexFirmwareInterpreter")

store.Add(plugin)