import whatap.net as net
import whatap.agent.counter.counter_manager as counter
import whatap.agent.control.control_handler as control_handler
import whatap.agent.counter.houseKeepingHelper as houseKeepingHelper
import whatap.downcheck as downcheck
import whatap.agentless.checkmain as agentless
import whatap.agent.conf.configure as config
import whatap.agent.cron.cronjob as cronjob
import whatap.agent.cron.script_manager as script_manager
import whatap.agent.control.agent_patch as agent_patch
from datetime import datetime, timedelta
import whatap.util.logging_util as logging_util
import whatap.util.thread_util as thread_util
import whatap.util.panic_util as panic_util
import whatap.agent.secure.security_master as secure
import whatap.net.tcpsession as tcpsession
import whatap.osinfo as osinfo
import whatap.pack as pack
import whatap.agent.data.data_pack as data_pack
from whatap.util.date_util import DateUtil as dateutil

module_loaded = datetime.now()


def syncProcgroupConfig():
    try:
        config.ClearProcgroupKeys()
    except Exception as e:
        logging_util.error("syncProcgroupConfig clear failed: {}".format(e))
    secu = secure.GetSecurityMaster()
    p = pack.NewParamPack()
    p.pcode = secu.pcode
    p.oid = secu.oid
    p.time = dateutil.now()
    p.id = net.PARAM_INFRA_AGENT_CONF_REQUEST
    p.putString("configId", "infra_process_group")
    data_pack.SendSecure(p)


def boot():
    net.startNet()
    syncProcgroupConfig()
    counter.startCounterManager()
    startExtension()
    control_handler.initControlHandler()
    downcheck.startHello()

    agentless.start()
    osinfo.InitSyslogRedirect()
    script_manager.init_script_manager()
    agent_patch.init_agent_patch()
    cronjob.start_cronjob()

    thread_util.async(houseKeepingHelper.startHouseKeeping)

def startExtension():
    import whatap.ext as _

def isOK():
    ret = True
    if datetime.now() - module_loaded > timedelta(minutes= config.GetConfig().HealthCheckCoolTime ):
        logging_util.debug("AgentBoot.IsOK step -0")
        secu = secure.GetSecurityMaster()
        logging_util.debug("AgentBoot.IsOK step -1")
        ret = secu.pcode != 0
        if not ret:
            message = "AgentBoot.IsOK pcode check {}".format(ret)
            logging_util.error(message)
            panic_util.AgentEventAsync({"event":"Error"}, {"log":message})
        ret = ret and (secu.oid != 0)
        if not ret:
            message = "AgentBoot.IsOK oid check {}".format(ret)
            logging_util.error(message)
            panic_util.AgentEventAsync({"event":"Error"}, {"log":message})
        ret = ret and tcpsession.isSessionOK()
        if not ret:
            message = "AgentBoot.IsOK session check {}".format(ret)
            logging_util.error(message)
            panic_util.AgentEventAsync({"event":"Error"}, {"log":message})
        ret = ret and counter.isOK()
        if not ret:
            message = "AgentBoot.IsOK counter check {}".format(ret)
            logging_util.error(message)
            panic_util.AgentEventAsync({"event":"Error"}, {"log":message})
    return ret

def boot_test():
    import os, sys
    from whatap.agent.counter.counter_manager import AGENT_VERSION
    from whatap.net.tcpsession import net_test
    import whatap.agent.conf.configure as conf

    logging_util.info("Agent Boot Test Start")

    c = config.GetConfig()
    if not c.Enabled:
        logging_util.error("Server Already Closed")
        print("FAIL: Server Already Closed")
        return False

    config_path = conf.GetConfigPath()
    logging_util.info("Config file : %s" % config_path)
    logging_util.info("Version : %s" % AGENT_VERSION)
    logging_util.info("PID : %s" % os.getpid())

    print("Config file : %s" % config_path)
    print("Version : %s" % AGENT_VERSION)
    print("PID : %s" % os.getpid())

    err = net_test()
    if err is not None:
        logging_util.error("Network Test Failed: %s" % err)
        print("FAIL: Network Test Failed: %s" % err)
        return False

    logging_util.info("Agent Boot Test Success")
    print("Agent Boot Test Success")
    return True

def end():
    pass
