import struct
import numpy as np


class AmmosIFDataHeader():

    @classmethod
    def from_bytes(cls, bytes):
        elements = struct.unpack('<IIQIIIQIIIIi', bytes)
        block_count = elements[0]
        block_length = int(elements[1])*4
        timestamp = np.datetime64(int(elements[2])*1000, 'ns')
        status = elements[3]
        source_id = elements[4]
        source_state = elements[5]
        frequency = elements[6]
        bandwidth = elements[7]
        sample_rate = elements[8]
        interpolation = elements[9]
        decimation = elements[10]
        voltage_ref = elements[11]

        return AmmosIFDataHeader(block_count, block_length, timestamp, status, source_id,
                                 source_state, frequency, bandwidth, sample_rate,
                                 interpolation, decimation, voltage_ref)

    def __init__(self, block_count, block_length, timestamp, status, source_id, source_state, frequency,
                 bandwidth, sample_rate, interpolation, decimation, voltage_ref):
        self.block_count = block_count
        self.block_length = block_length
        self.timestamp = timestamp
        self.status = status
        self.source_id = source_id
        self.source_state = source_state
        self.frequency = frequency
        self.bandwidth = bandwidth
        self.sample_rate = sample_rate
        self.interpolation = interpolation
        self.decimation = decimation
        self.voltage_ref = voltage_ref

    def header_size(self):
        return 56

    def __str_(self):
        output = ("\nGlobal frame body data header\n" +
                  "-----------------------------\n" +
                  "Block count:" + str(self.block_count) + "\n" +
                  "Block length:" + str(self.block_length) + "\n" +
                  "Time stamp:" + str(self.timestamp) + "\n" +
                  "Frequency:" + str(self.frequency) + "\n" +
                  "Bandwidth:" + str(self.bandwidth) + "\n" +
                  "Sample rate:" + str(self.sample_rate) + "\n")
        return output
