import binascii
import datetime
from Log import LOG
from protocols import protos
import struct

#ignore_list = [5637, 881, 951, 201, 251, 5745, 176, 883, 5632, 6061, 170, 6454, 5816, 6316, 210, 220, 175, 226, 6827, 5968, 6622, 6713, 6830, 6438, 5537, 5502, 5747, 5557, 946, 5794]
class Message():
    def __init__(self, raw_data, protocol, message_size, message_type, message_with_headers, packet, validated):
        if str(protocol) in protos.keys():
            self.valid = True
        else:
            self.valid = False
            return
        self.protocol = protos[str(protocol)]
        self.protocol_id = protocol
        self.missing = False
        self.data = raw_data
        self.packet = packet
        self.full_message = message_with_headers
        self.size = message_size
        self.type = message_type
        if (len(self.packet) - self.type - self.size - 2) < 0 or (self.size + self.type + 2 > validated):
            self.missing = True

    def print_infos(self):
        LOG.debug("{:>4} - {} ({}: {}) - (remain: {})".format(self.protocol_id, self.protocol, self.type, self.size, len(self.packet) - self.type - self.size - 2))
        self.dump_message()

    def dump_message(self, full=True):
        if full == True:
            to_print = self.packet
        else:
            to_print = self.data
        i = 0
        line = 0
        ret = ''
        ret_str = ''
        total_len = len(to_print)
        for i in range(0, total_len - 1):
            val = struct.unpack(">B", to_print[i:i+1])[0]
            if line == 16:
                LOG.dump(ret, endv=" | ")
                LOG.dump(ret_str)
                ret = ''
                ret_str = ''
                line = 0
            ret += (str(hex(val)).split('0x')[1].zfill(2)) + " "
            if chr(val).isprintable():
                ret_str += chr(val)
            else:
                ret_str += '.'
            line += 1
        LOG.dump(f"{ret:<48}", endv=" | ")
        LOG.dump(ret_str)
