"""I provide an AMMOS global frame header."""
import struct
from ammosreader import logger

class AmmosGlobalFrameHeader:
    """I implement an AMMOS global frame header."""

    MAGIC_WORD = "726574fb"
    HEADER_SIZE = 24

    @classmethod
    def from_bytes(cls, bytes):
        """I create a new AmmosGlobalFrameHeader from bytes."""
        assert len(bytes) == cls.HEADER_SIZE

        elements = struct.unpack('<4s4s4s4s4s4s', bytes)

        magic_word = elements[0].hex()

        logger.debug("Header created")
        if magic_word != cls.MAGIC_WORD:
            return None

        frame_length = (int.from_bytes(elements[1], byteorder='little')*4)

        running_frame_number = (int.from_bytes(elements[2], byteorder='little'))

        frame_type = (int.from_bytes(elements[3], byteorder='little'))

        data_header_length = 4 * int.from_bytes(elements[4], byteorder='little')

        reserved = elements[5]

        return AmmosGlobalFrameHeader(magic_word, frame_length, running_frame_number,
                                      frame_type, data_header_length, reserved)

    def __init__(self, magic_word, frame_length, running_frame_number, frame_type, data_header_length, reserved):
        """I return a new instance of myself initialized with above parameters."""
        if magic_word != type(self).MAGIC_WORD:
            logger.error("Wrong magic word found")
            self.magic_word = magic_word
        else:
            self.magic_word = magic_word
            self.frame_length = frame_length
            self.running_frame_number = running_frame_number
            self.frame_type = frame_type
            self.data_header_length = data_header_length
            self.reserved = reserved

    def __str__(self):
        """I return the string representation of myself."""
        output = ("Global frame header info\n" +
                  "------------------------\n" +
                  "Magic word:" + str(self.magic_word) + "\n" +
                  "Frame length:" + str(self.frame_length) + "\n" +
                  "Running frame:" + str(self.running_frame_number) + "\n" +
                  "Frame Type:" + str(self.frame_type) + "\n" +
                  "Data header length:" + str(self.data_header_length) + "\n")
        return output
