from whatap.pack.pack import Pack
from whatap.pack.pack_enum import PackEnum
from whatap.value.null_value import NullValue
from whatap.value.value_enum import ValueEnum
from whatap.value.text_value import TextValue
from whatap.value.decimal_value import DecimalValue
import whatap.value.value as value

from StringIO import StringIO

class ParamPack(Pack):
    def __init__(self):
        Pack.__init__(self)

        self.id =0
        self.table = {}
        self.request = 0
        self.response = 0

    def get(self, key ):
        o = self.table.get(key)
        if o is None:
            return NullValue()

        return o

    def getMap(self, key):
        return self.table.get(key)

    def getString(self, key) :
        o = self.get(key)
        if o.getValueType() == ValueEnum.TEXT :
            return o.value

        return ""

    def putString(self, key , v ):
        self.put(key, TextValue(v))

    def putLong(self, key , v ):
        self.put(key, DecimalValue(v))

    def put(self, key , v ) :
        self.table[key]= v

    def clear(self):
        self.clear()

    def size(self):
        len(self.table)

    def keys(self):
        return self.table.keys()

    def getPackType(self):
        return PackEnum.PACK_PARAMETER

    def write(self, dout ):
        super(ParamPack, self).write(dout)
        dout.writeInt(self.id)
        dout.writeDecimal(self.request)
        dout.writeDecimal(self.response)
        dout.writeDecimal(len(self.table))

        keys = self.keys()
        for key in keys:
            v = self.table.get(key)
            dout.writeText(key)
            value.writeValue(dout, v)

    def read(self, din ):
        super(ParamPack, self).read(din)
        self.id = din.readInt()
        self.request = din.readDecimal()
        self.response = din.readDecimal()
        count = int(din.readDecimal())
        for t in range(count):
            key = din.readText()
            v = value.readValue(din)
            self.table[key]= v

    def toResponse(self):
        if self.request == 0 :
            return self

        self.response = self.request
        self.request = 0

        return self

    def toString(self):
        buffer =StringIO()
        buffer.write("ParamPack")
        buffer.write("\nid=")
        buffer.write(self.id)
        buffer.write("\nrequest=")
        buffer.write(self.request)
        buffer.write("\nresponse=")
        buffer.write(self.response)
        buffer.write("\n")
        buffer.write(self.table)
        return buffer.getvalue()
