#!/usr/bin/env python3
# -*- coding:utf-8 -*-
try:
    import sys
    from datetime import datetime
    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 ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))

monthdic = {"Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10,
            "Nov": 11, "Dec": 12}


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

    def doCheck(self):
        self.result.rst = ResultStatus.OK
        timelist = []
        gaussPro = "gs_gtm,om_monitor,gaussdb,cm_agent,cm_server"
        cmd = "ps -C %s -o lstart,args | grep -v grep | grep -v 'om_monitor' 2>/dev/null" % gaussPro
        output = SharedFuncs.runShellCmd(cmd, self.user, self.mpprcFile)
        for line in output.splitlines()[1:]:
            resultList = line.split()
            year = resultList[4]
            month = monthdic[resultList[1]]
            day = resultList[2]
            time = resultList[3]
            timestring = "%s-%s-%s %s" % (year, month, day, time)
            dattime = datetime.strptime(timestring, '%Y-%m-%d %H:%M:%S')
            timelist.append(dattime)
        if (timelist):
            mintime = timelist[0]
            maxtime = timelist[0]
        else:
            mintime = None
            maxtime = None
        for tmpdatetime in timelist:
            if (tmpdatetime < mintime):
                mintime = tmpdatetime
            elif (tmpdatetime > maxtime):
                maxtime = tmpdatetime
        if (maxtime and mintime):
            if (int((maxtime - mintime).days) > 0 or int((maxtime - mintime).seconds) > 300):
                self.result.rst = ResultStatus.WARNING
                self.result.val = output
            else:
                self.result.rst = ResultStatus.OK
                self.result.val = output

    def postAnalysis(self, itemResult):
        timedic = {}
        valdic = {}
        allhost = []
        nghost = []
        Mintime = None
        itemResult.standard = self.standard
        for v in itemResult.getLocalItems():
            output = v.val
            timelist = self.get_time_list(output)
            if timelist:
                mintime = timelist[0]
                maxtime = timelist[0]
            else:
                mintime = None
                maxtime = None
            for tmpdatetime in timelist:
                if tmpdatetime < mintime:
                    mintime = tmpdatetime
                elif tmpdatetime > maxtime:
                    maxtime = tmpdatetime
            timelist = []
            if maxtime and mintime:
                timelist.append(mintime)
                timelist.append(maxtime)
                if Mintime and Mintime < mintime:
                    pass
                else:
                    Mintime = mintime
            if timelist:
                timedic[v.host] = timelist
                valdic[v.host] = output
                allhost.append(v.host)
        for host in allhost:
            hostmax = timedic[host][1]
            if int((hostmax - Mintime).days) > 0 or int((hostmax - Mintime).seconds) > 300:
                if host not in nghost:
                    nghost.append(host)

        if nghost:
            itemResult.rst = ResultStatus.WARNING
            resultStr = ""
            for host in nghost:
                resultStr = "%s%s:\n%s\n" % (resultStr, host, valdic.get(host))
            itemResult.analysis = resultStr
        else:
            itemResult.rst = ResultStatus.OK
            itemResult.analysis = "Basically ,all the gaussdb process start at the same time"
        return itemResult

    def get_time_list(self, result):
        timelist = []
        for line in result.splitlines()[1:]:
            resultList = line.split()
            year = resultList[4]
            month = monthdic[resultList[1]]
            day = resultList[2]
            time = resultList[3]
            timestring = "%s-%s-%s %s" % (year, month, day, time)
            dattime = datetime.strptime(timestring, '%Y-%m-%d %H:%M:%S')
            timelist.append(dattime)
        return timelist
