#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
    from gspylib.os.gsnetwork import g_network
    from gspylib.os.gsfile import g_file
    from gspylib.os.gsplatform import g_Platform
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))

EXPECTED_RXTX = 4096
NEED_REPAIR = []

class CheckRXTX(BaseItem):
    def __init__(self):
        super(CheckRXTX, self).__init__(self.__class__.__name__)

    def doCheck(self):
        global NEED_REPAIR
        flag = "Normal"
        for networkCardNum in self.service_network_adapts:
            try:
                tx_value = str(g_Platform.getNetworkRXTXValueByNICNum(networkCardNum, 'tx')).strip()
            except Exception:
                tx_value = ""
            try:
                rx_value = str(g_Platform.getNetworkRXTXValueByNICNum(networkCardNum, 'rx')).strip()
            except Exception:
                rx_value = ""
            if not rx_value or not tx_value:
                flag = "Error"
                self.result.val = "%sFailed to obtain network card [%s] RX or TX value." % (self.result.val,
                                                                                            networkCardNum)
                continue

            if (int(rx_value) < int(EXPECTED_RXTX)) or (int(tx_value) < int(EXPECTED_RXTX)):
                flag = "Error"
                self.result.val = "%sNetWork[%s]\nRX: %s\nTX: %s\n" % (self.result.val, networkCardNum,
                                                                       rx_value, rx_value)
                NEED_REPAIR.append(networkCardNum)
        self.result.raw = self.result.val
        if flag == "Normal":
            self.result.rst = ResultStatus.OK
        else:
            self.result.rst = ResultStatus.NG

    def doSet(self):
        for networkCardNum in NEED_REPAIR:
            cmd = "%s -G %s %s %d" % (g_Platform.getEthtoolCmd(), networkCardNum.NICNum, "rx", EXPECTED_RXTX)
            cmd = "%s;%s -G %s %s %d" % (cmd, g_Platform.getEthtoolCmd(), networkCardNum.NICNum, "tx", EXPECTED_RXTX)
            SharedFuncs.runShellCmd(cmd)
