from datetime import datetime
from whatap.pack.pack_enum import PackEnum

class Pack(object):

    _data_output_x = None
    def __init__(self):
        self.pcode = 0
        self.oid = 0
        self.time = 0
    
    def __repr__(self):
        to_str = '{0}: '.format(type(self).__name__)
        
        data = self.__dict__.copy()
        for key, value in data.items():
            if key == 'time':
                value = datetime.fromtimestamp(value / 1000) \
                    .strftime('%Y-%m-%d %H:%M:%S')
                
            to_str += '{0}={1}, '.format(key, value)
        return to_str
    

    @classmethod
    def get_output_buffer(cls):
        if cls._data_output_x is None:
            from whatap.io.data_outputx import DataOutputX
            cls._data_output_x = DataOutputX()
        cls._data_output_x.buffer[:] = []
        return cls._data_output_x

    def getPackType(self):
        return 0
    
    def write(self, dout):
        dout.writeDecimal(self.pcode)
        dout.writeInt(self.oid)
        dout.writeLong(self.time)
    
    def read(self, din):
        self.pcode = din.readDecimal()
        self.oid = din.readInt()
        self.time = din.readLong()
        return self

    @staticmethod
    def writePack(out, p):
        out.writeShort(p.getPackType())
        p.write(out)
        return out

    @staticmethod
    def readPack( in_ ):
        t= in_.readShort()
        v= PackEnum.create(t)
        v.read(in_)
        return v

    @staticmethod
    def toBytesPack(p):
        out = Pack.get_output_buffer()
        Pack.writePack(out, p)
        return out.toByteArray()

    @staticmethod
    def toPack(b):
        from whatap.io.data_inputx import DataInputX
        in_ = DataInputX(b)
        return Pack.readPack(in_)

    @staticmethod
    def toBytesPackECB(p , fmtLen ):
        out = Pack.get_output_buffer()
        Pack.writePack(out, p)
        remainder = out.size() % fmtLen
        if remainder > 0:
            out.write('\0'*(fmtLen-remainder))

        return out.toByteArray()
