import whatap.pack.tagcount_pack as tagcount_pack
import whatap.osinfo as osinfo
import whatap.agent.secure.security_master as secure
import whatap.agent.conf.configure as config
from whatap.util.hash_util import HashUtil as hashutil
from whatap.value.list_value import ListValue
from whatap.osinfo.os_parameter_common import parse_custom_params


class TaskInfraOsParameter:
    OS_PARAMETER = "infra_os_parameter{h1}"

    def __init__(self, interval=300):
        self.intervalValue = interval
        self.recType = 2

    def interval(self):
        return self.intervalValue

    def _custom_params(self):
        try:
            raw = config.GetConfig().getProperty("InfraOsParameterCustom", "")
        except Exception:
            raw = ""
        return parse_custom_params(raw)

    def process(self, os_, pcode, oid, now):
        params = osinfo.GetOsParameterList(self._custom_params())
        if not params:
            return None

        secu = secure.GetSecurityMaster()
        p = tagcount_pack.TagCountPack()
        p.pcode = pcode
        p.oid = oid
        p.time = now
        p.category = TaskInfraOsParameter.OS_PARAMETER
        p.putTag("oname", str(secu.oname))
        p.putTag("!rectype", str(self.recType))

        idList = ListValue()
        parameterList = ListValue()
        categoryList = ListValue()
        osList = ListValue()
        valueList = ListValue()
        customList = ListValue()

        for item in params:
            # @id is the (parameter + category) combination (SERVER-1794 spec)
            key = hashutil.hashFromString("{}{}".format(item.parameter, item.category))
            idList.addLong(key)
            parameterList.addString(item.parameter if item.parameter else "")
            categoryList.addString(item.category if item.category else "")
            osList.addString(item.os if item.os else "")
            valueList.addString(str(item.value) if item.value is not None else "")
            customList.addBoolean(bool(item.custom))

        p.put("@id", idList)
        p.put("parameter", parameterList)
        p.put("category", categoryList)
        p.put("os", osList)
        p.put("value", valueList)
        p.put("custom", customList)

        return [p]
