import whatap.agent.secure.security_master as secure
import whatap.agent.data.data_text as data
from whatap.pack.pack_enum import PackEnum
import whatap.pack as pack
from whatap.util.date_util import DateUtil as dateutil
import whatap.net as net
import whatap.agent.conf.configure as conf
from whatap.util.ip_util import IPUtil as iputil
import whatap.util.logging_util as logging_util
import platform, os, socket
import whatap.osinfo as osinfo
import whatap.value as value

class TaskHostInfo:
    def __init__(self, agent_version=""):
        self.firstSent = False
        self.agent_version = agent_version

    def interval(self):
        return 3600

    def process(self, os_ , pcode , oid , now ) :
        secu = secure.GetSecurityMaster()
        if secu.oid == 0 :
            return None

        return self.sendHostInfo()

    def sendHostInfo(self):
        secu = secure.GetSecurityMaster()
        p = pack.NewParamPack()
        p.pcode = secu.pcode
        p.oid = secu.oid
        p.time = dateutil.now()
        p.id = net.PARAM_INFRA_HOSTINFO
        hostInfoMap = value.NewMapValue()
        hostname = socket.gethostname()
        hostInfoMap.putString("hostname", hostname)
        hostInfoMap.putString("ipAddress", iputil.toString(secu.publicip))

        osinfodict = osinfo.GetServerInfoV2()
        for k, v in osinfodict.items():
            if k == "lCores" or k == "nCores" or k == "memTotal" or k == "uptime":
                try:
                    hostInfoMap.putLong(k, int(v))
                except (ValueError, TypeError), e:
                    logging_util.error("value error", e)
                    continue
            else:
                hostInfoMap.putString(k, v)
        hostInfoMap.putString("whatap_infradVersion", self.agent_version)

        p.put("table", value.NewTextValue("server_inventory"))
        p.put("key", value.NewDecimalValue(p.oid))
        p.put("data", hostInfoMap)

        return p
