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 SatoFirmwareInterpreter")

class SatoFirmwareInterpreter(FirmwareInterpreter):

    def GetMetadata(self, fileName, fileBytes, *args):
        models = List[str]()
        version = ""
        return FirmwareMetadata(version, models)

        
    def ValidateVersion(self, rawVersion, *args):
        versionPattern = r'r\d+'
        version_match = re.search(versionPattern, rawVersion)
        if version_match:
            return True
        return False
        

    def CompareVersions(self, deviceStateVersionRaw, firmwareFileVersionRaw):
        versionPattern = r'(?<=r)\d+'
        deviecStateVersionMatch = re.search(versionPattern, deviceStateVersionRaw)
        if not deviecStateVersionMatch:
            raise ValueError('Could not interpret device state version') 
        firmwareFileVersionMatch = re.search(versionPattern, firmwareFileVersionRaw)
        if not firmwareFileVersionMatch:
            raise ValueError('Could not interpret firmware file version') 
        deviecStateVersionMatchInt = int(deviecStateVersionMatch.group())
        firmwareFileVersionMatchInt = int(firmwareFileVersionMatch.group())
        if deviecStateVersionMatchInt > firmwareFileVersionMatchInt:
            return 1
        elif firmwareFileVersionMatchInt > deviecStateVersionMatchInt:
            return -1
        else:
            return 0


plugin = SatoFirmwareInterpreter("SatoFirmwareInterpreter")

store.Add(plugin)