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

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

print("Loading CabFirmwareInterpreter")

class CabFirmwareInterpreter(FirmwareInterpreter):

    def GetMetadata(self, fileName, fileBytes, *args):
        #convert file bytes to string
        #models
        models = List[str]()
        version = fileName.split('_')[0]
        version = re.sub(r'^(\d)(\d{2})(\d)$', r'\1.\2.\3', version)
        fileString = bytes(fileBytes).decode('utf-8', errors='ignore')
        if fileString.startswith("y42;9262"):
            models.AddRange([
                'SQUIX 2/300', 'SQUIX 2/300P', 'SQUIX 2/600', 'SQUIX 2/600P', 
                'SQUIX 4.3/200', 'SQUIX 4.3/200P', 'SQUIX 4.3/200M', 'SQUIX 4.3/200MP', 
                'SQUIX 4.3/200MT', 'SQUIX 4.3/300', 'SQUIX 4.3/300P', 'SQUIX 4.3/300M', 
                'SQUIX 4.3/300MP', 'SQUIX 4.3/300MTUIX', 'SQUIX 4/300', 'SQUIX 4/300P', 
                'SQUIX 4/300M', 'SQUIX 4/300MP', 'SQUIX 4/300MT', 'SQUIX 4/600', 
                'SQUIX 4/600P', 'SQUIX 4/600M', 'SQUIX 4/600MP', 'SQUIX 4/600MT', 
                'SQUIX 6.3/200', 'SQUIX 6.3/200P', 'SQUIX 6.3/300', 'SQUIX 6.3/300P', 
                'SQUIX 8.3/300', 'SQUIX 8.3/300P'
            ])

        return FirmwareMetadata(version, models)
        
    def ValidateVersion(self, rawVersion, *args):
        try:
            tuple(map(int, rawVersion.split('.')))
            return True
        except:
            return False
    
    def CompareVersions(self, deviceStateVersionRaw, firmwareFileVersionRaw):
        
        try:
            deviceStateVersionInt = int(deviceStateVersionRaw.Replace('.', ''))
            firmwareFileVersionInt = int(firmwareFileVersionRaw.Replace('.', ''))

            if deviceStateVersionInt > firmwareFileVersionInt:
                return 1
            elif firmwareFileVersionInt > deviceStateVersionInt:
                return -1
            else:
                return 0
        except:
            raise
   

    
plugin = CabFirmwareInterpreter("CabFirmwareInterpreter")

store.Add(plugin)