from whatap.pack.pack import Pack
from whatap.pack.pack_enum import PackEnum
from whatap.io.data_outputx import DataOutputX
from whatap.value.map_value import MapValue
import whatap.value.value as value
from whatap.util.hash_util import HashUtil

from StringIO import StringIO

class TagCountPack(Pack):
    def __init__(self, category= None):
        Pack.__init__(self)

        self.category = category
        self.taghash = 0
        self.tags = MapValue()
        self.fields = MapValue()

    def getPackType(self):
        return PackEnum.PACK_TAGCOUNT

    def write(self, dout ):
        super(TagCountPack, self).write(dout)

        dout.writeByte(0)
        dout.writeText(self.category)
        if self.taghash == 0 and self.tags.size() > 0:
            tagIO = DataOutputX()
            value.writeValue(tagIO, self.tags)
            tagbytes = tagIO.toByteArray()
            self.taghash = HashUtil.hash64(tagbytes)
            dout.writeDecimal(self.taghash)
            dout.write(tagbytes)
        else:
            dout.writeDecimal(self.taghash)
            value.writeValue(dout, self.tags)

        value.writeValue(dout, self.fields)

    def put(self, key, value):
        if isinstance(value, int) or isinstance(value, long):
            self.fields.putLong(key, value)
        elif isinstance(value, float):
            self.fields.putFloat(key, value)
        elif isinstance(value, str):
            self.fields.putString(key, value)
        else:
            self.fields.put(key, value)

    def putTag(self, key, value):
        self.tags.putString(key, value)

    def read(self, din ):
        super(TagCountPack, self).read(din)
        din.readByte()
        self.category = din.readText()
        self.tags = value.readValue(din)
        self.fields = value.readValue(din)

    def size(self):
        return self.fields.size()

    def isempty(self):
        return self.fields.size() < 1

    def clear(self):
        self.fields.clear()
