#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
except ImportError as e:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(e))


class CheckCPU(BaseItem):
    def __init__(self):
        super(CheckCPU, self).__init__(self.__class__.__name__)
        self.idle = None
        self.wio = None
        self.standard = None

    def preCheck(self):
        # check the threshold was set correctly
        if ("StandardCPUIdle" not in self.threshold.keys()
                or "StandardWIO" not in self.threshold.keys()):
            raise Exception("threshold can not be empty")
        if (not self.threshold['StandardCPUIdle'].isdigit() or not self.threshold['StandardWIO'].isdigit()):
            raise Exception("The threshold StandardCPUIdle and StandardWIO must be integer.")
        self.idle = self.threshold['StandardCPUIdle']
        self.wio = self.threshold['StandardWIO']

        # format the standard by threshold
        self.standard = self.standard.decode().format(idle=self.idle, iowait=self.wio)

    def doCheck(self):
        cmd = "sar 1 5 2>&1"
        output = SharedFuncs.runShellCmd(cmd)
        self.result.raw = output
        # check the result with threshold
        d = next(n.split() for n in output.splitlines() if "Average" in n)
        iowait = d[-3]
        idle = d[-1]
        rst = ResultStatus.OK
        vals = []
        if (float(iowait) > float(self.wio)):
            rst = ResultStatus.NG
            vals.append("The %s actual value %s %% is greater than expected value %s %%" % ("IOWait", iowait, self.wio))
        if (float(idle) < float(self.idle)):
            rst = ResultStatus.NG
            vals.append("The %s actual value %s %% is less than expected value %s %%" % ("Idle", idle, self.idle))
        self.result.rst = rst
        if (vals):
            self.result.val = "\n".join(vals)
