import struct

from .buffer import Buffer
from .formatter import Formatter

class Messages(object):
    def __init__(self):
        self.__messages = {}

    def load(self, resources):
        buf = Buffer()

        resources.forEachInGroup('messages', lambda res: self.loadFromResource(res, buf))

    def loadFromResource(self, resource, buf):
        if not resource:
            return

        cnt = resource.getVariantsCount()

        for variant in resource.variants:
            if variant:
                try:
                    score = variant.i18nScore
                    data = variant.getData()
                    self.loadBundle(score, data)
                except Exception as e:
                    print("Error loading text bundle {}: {}".format(resource.getName(), e))

                    raise

    def loadBundle(self, score, data):
        if data[0:3] != b"CMF":
            raise Exception("Invalid format of message file!")

        version = struct.unpack('i', data[3:7])[0]
        if version != 1:
            raise Exception("Unknown version of message file!")

        offset = struct.unpack('i', data[len(data) - 4:])[0]
        cnt = struct.unpack('i', data[offset:offset + 4])[0]
        offset += 4

        for i in range(0, cnt):
            sz = struct.unpack('i', data[offset:offset + 4])[0]
            offset += 4;

            if sz > 0:
                name = data[offset:offset + sz].decode('utf-8')
                msgOffset = struct.unpack('i', data[offset + sz:offset + sz + 4])[0]

                if name in self.__messages:
                    ss = self.__messages[name]
                    if ss['score'] <= score:
                        ss['score'] = score
                        ss['message'] = Formatter(data, msgOffset)
                else:
                    self.__messages[name] = {
                        "score": score,
                        "message": Formatter(data, msgOffset),
                    }

            offset += sz + 4

msg = Messages()
