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

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

print("Loading BixolonFirmwareInterpreter")

class BixolonFirmwareInterpreter(FirmwareInterpreter):
    XM7_40_40R_FirmwareSignature = b"\x1b\x23\x6d\x00\xa3"
    XD_XT5_Label_FirmwareSignature = b"\x1b\x23\x6d\x00\x40"
    SignaturesLength = 5

    def GetMetadata(self, fileName, fileBytes, *args):
        #models
        models = List[str]()
        if fileBytes is not None and len(fileBytes) > self.SignaturesLength:
            fileSignatureBytes = bytes(fileBytes[:self.SignaturesLength])
            if fileSignatureBytes == self.XM7_40_40R_FirmwareSignature:
                models.AddRange(["XM7-40R"])
            if fileSignatureBytes == self.XD_XT5_Label_FirmwareSignature:
                models.AddRange(["XD5-40tR", "XD5-43tR", "XT5-40NR", "XT5-43NR"])
        version = " "
        return FirmwareMetadata(version, models)

        
    def ValidateVersion(self, rawVersion, *args):
        versionPattern = r'^[A-Z]\d{2}\.\d{2} (STD|SOTI) \d{6}$'
        version_match = re.search(versionPattern, rawVersion)
        if version_match:
            return True
        return False


    
    def CompareVersions(self, deviceStateVersionRaw, firmwareFileVersionRaw):
        versionPattern = r'\D'
        deviecStateVersionInt = re.sub(versionPattern, '', deviceStateVersionRaw)
        try:
            deviecStateVersionInt = int(deviecStateVersionInt)
        except:
            raise ValueError('Could not interpret device state version')

        firmwareFileVersionInt = re.sub(versionPattern, '', firmwareFileVersionRaw)
        try:
            firmwareFileVersionInt = int(firmwareFileVersionInt)
        except:
            raise ValueError('Could not interpret firmware file version') 
        
        if deviecStateVersionInt > firmwareFileVersionInt:
            return 1
        elif firmwareFileVersionInt > deviecStateVersionInt:
            return -1
        else:
            return 0
        


plugin = BixolonFirmwareInterpreter("BixolonFirmwareInterpreter")

store.Add(plugin)