#!/usr/bin/python3
#date -d @1234567890
# sudo nano /etc/collectd/collectd.conf
from globalSettings import *
from global_func import *
import subprocess
import rrdtool
import sys
import time
import os
import json
import sqlite3
import cgi
import cgitb

cgitb.enable()
#from db import *

lyraTLElement = ["tempTL.rrd",
                "psuTL.rrd", "fanTL.rrd", "opTL.rrd","diskTL.rrd"]

device = DeviceName

tempRRD = lyraTLElement[0]
psuRRD = lyraTLElement[1]
fanRRD = lyraTLElement[2]
opRRD = lyraTLElement[3]
diskRRD = lyraTLElement[4]
cmd_Id = get_ccm_command_id()
def read_CCM():
    if CCM:
        cmd="test_response"
        name="CCM"
        action="CCM"
        message="set,element=test_response,element_name={0},args=2,action={1},uuid={2}".format(name,action,cmd_Id)
        send_ccm_msg(message) 
        response = get_ccm_response(cmd_Id)
        delete_ccm_response(cmd_Id)
        #response = json.JSONEncoder().encode({"status": "success", "description": "CCM state: OK, License state: OK"})
        return response


def Metrics(Mtype, arg):
    deviceMetrics = []
    if Mtype == 'I':
        if arg == "GUI":
            deviceMetrics = driveRRD
        else:
            deviceMetrics = driveRRD

    elif Mtype == 'T':
        if arg == "GUI":
            deviceMetrics = tempRRD
        else:
            deviceMetrics = tempRRD

    elif Mtype == "P":
        if arg == "GUI":
            deviceMetrics = psuRRD
        else:
            deviceMetrics = psuRRD

    elif Mtype == "F":
        if arg == "GUI":
            deviceMetrics = fanRRD
        else:
            deviceMetrics = fanRRD

    elif Mtype == "O":
        if arg == "GUI":
            deviceMetrics = opRRD
        else:
            deviceMetrics = opRRD

    elif Mtype == "D":
        if arg == "GUI":
            deviceMetrics = diskRRD
        else:
            deviceMetrics = diskRRD

    else:
        deviceMetrics = ['None defined']

    return deviceMetrics


if GUI == true:
    import cgi
    import cgitb
    cgitb.enable()

if GUI == true:
    form = cgi.FieldStorage()
    request_Type = form.getvalue('requestType')
    #deviceList = form.getvalue('deviceList')
    device = form.getvalue('device')
    scale = form.getvalue('scale')
    NumHorizontal_points_in_graph = form.getvalue(
        'NumHorizontal_points_in_graph')
    #metrics = form.getvalue('metrics')
    getMetricType = form.getvalue('MetricType')
else:

    MetricChoices = []
    print('1. minutes')
    print('2. hours')
    print('3. days')
    print('4. weeks')
    print('5. months')
    choice = int(input("select TimeBase==>"))
    if (choice == 1):
        scale = "mins"
        NumHorizontal_points_in_graph = 10
    if (choice == 2):
        scale = "hours"
        NumHorizontal_points_in_graph = 60
    if (choice == 3):
        scale = "days"
        NumHorizontal_points_in_graph = 60
    if (choice == 4):
        scale = "weeks"
        NumHorizontal_points_in_graph = 60
    if (choice == 5):
        NumHorizontal_points_in_graph = 60
        scale = "months"

    print('1. i_DriveStats')
    print('2. temp Stats')
    print('3. psu Stats')
    print('4. fan_Stats')
    print('5. op_Stats')
    print('6. disk_Stats')

    choice = int(input("select cgi function==>"))

    if (choice == 1):
        request_Type = 'I'
        deviceList = 'I'
        MetricChoices = Metrics(deviceList, 'GUI')
        print(MetricChoices)

    elif (choice == 2):
        request_Type = "T"
        deviceList = "T"
        MetricChoices = Metrics(deviceList, 'GUI')
        print(MetricChoices)

    elif (choice == 3):
        request_Type = "P"
        deviceList = "P"
        MetricChoices = Metrics(deviceList, 'GUI')
        print(MetricChoices)

    elif (choice == 4):
        request_Type = "F"
        deviceList = "F"
        MetricChoices = Metrics(deviceList, 'GUI')
        print(MetricChoices)

    elif (choice == 5):
        request_Type = "O"
        deviceList = "O"
        MetricChoices = Metrics(deviceList, 'GUI')
        print(MetricChoices)

    elif (choice == 6):
            request_Type = "D"
            deviceList = "D"
            MetricChoices = Metrics(deviceList, 'GUI')
            print(MetricChoices)

    else:
        print("Choice Not Defined")

    print("Request_Type="+str(request_Type))

retentionMins = 60
minutesPerPoint = 6

if scale == "mins":
    retentionMins = 60
    minutesPerPoint = 6

elif scale == "hours":
    retentionMins = 24 * 60
    minutesPerPoint = 30

elif scale == "days":
    retentionMins = int(7 * 24 * 60)
    minutesPerPoint = int(6*60)

elif scale == "weeks":
    retentionMins = int(4*7*24*60)
    minutesPerPoint = int(7*6*60)


def guiDeviceResult(rrdPath, deviceList, GUIdeviceList):
    result_all = dict()
    #minutesPerPoint = retentionMins / int(NumHorizontal_points_in_graph)
    # retentionMins =10  ### Commented By Divya TO TEST
    # minutesPerPoint=1 ### Commented By Divya TO TEST
    retentionSecs = retentionMins * 60

    i = 0
    for device in deviceList:
        rrdDevice = device
        #DataFile = rrdPath + rrdDevice + "/" + rrdFile
        DataFile = rrdPath + "/" + rrdDevice
        now = int(time.time())
        now = now-60
        startTime = now - retentionSecs
        endTime = now
        secondsPerPoint = minutesPerPoint * 60
        startTime = int(startTime/minutesPerPoint)
        startTime = int(startTime*minutesPerPoint)
        endTime = int(endTime/minutesPerPoint)
        endTime = int(endTime*minutesPerPoint)
        # print "startTime",startTime
        # print "endTime",endTime
        # print time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.localtime(endTime))
        if not os.path.isfile(DataFile):
            GUIdevice = GUIdeviceList[i]
            result_all[GUIdevice] = [{"epoch_range":[]}, {"columns":[]},{"ccm":CCM}, {"device":str(deviceList)}]
            return result_all
        (timeInfo, columns, rows) = rrdtool.fetch(DataFile, 'AVERAGE', '-r', str(secondsPerPoint), '-s',
                                                  str(startTime), '-e', str(endTime))
        rows.pop()  # remove the last datapoint because RRD sometimes gives funky values
        # print "printing timeInfo"
        # print timeInfo
        colWidth = len(columns)
        # print "column width=" + str(colWidth)
        # print columns
        # rows.pop()
        # rows.pop
        lenRows = len(rows)
        # print "length of rows =" + str(lenRows)
        # print "column width=" + str(len(columns))
        # print columns
        result = []
        epoch_range = dict()
        epoch_range['epoch_range'] = list(timeInfo)
        result.append(epoch_range)
        cols = dict()
        cols['columns'] = columns
        result.append(cols)
        # print len(rows)
        for row in rows:
            # print row
            # print row[0]
            temp = dict()
            if row[0] == None:
                continue
            if (colWidth == 1):
                #temp['val1'] = round(float(row[0]), 2)
                val1 = round(float(row[0]), 2)
                temp['row'] = [val1]
            if (colWidth == 2):
                #temp['val1'] = round(float(row[0]), 2)
                #temp['val2'] = round(float(row[1]), 2)
                val1 = round(float(row[0]), 2)
                val2 = round(float(row[1]), 2)
                temp['row'] = [val1, val2]
            if (colWidth == 3):

                val1 = round(float(row[0]), 2)
                val2 = round(float(row[1]), 2)
                val3 = round(float(row[2]), 2)
                temp['row'] = [val1, val2, val3]

            if (colWidth == 4):
                val1 = round(float(row[0]), 2)
                val2 = round(float(row[1]), 2)
                val3 = round(float(row[2]), 2)
                val4 = round(float(row[3]), 2)
                temp['row'] = [val1, val2, val3, val4]

            if (colWidth > 4):
                temp['row'] = row
            result.append(temp)
        GUIdevice = GUIdeviceList[i]
        i = i+1
        result_all[GUIdevice] = result
    result = json.loads(read_CCM())
    if result["status"] == "fail":
        CCM = 0
    else:
        CCM = 1
    result_all["ccm"] = CCM
    result_all["deviceList"] = str(deviceList)
    return result_all


def Get_rrdPath():
    #rrdPath = "/home/pilot"
    # rrdPath = "/var/log/rrdFiles"
    return RRD_Files_Path


def EpochToTime(epoch):
    mytime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch))

  # print mytime


def get_Metrics(Mtype):
    deviceMetrics = []
    arg = "GUI"
    deviceMetrics = Metrics(Mtype, arg)
    result = {"metrics": deviceMetrics}
    print(json.JSONEncoder().encode(result))


def read_iDrive():
    deviceList = [driveRRD]

    rrdPath = Get_rrdPath()

    #metrics = form.getvalue('metrics')
    rrdFile = driveRRD
    GUIdeviceList = []
    GUIdeviceList.append("iDrive")
    result_all = guiDeviceResult(rrdPath, deviceList, GUIdeviceList)
    print(json.JSONEncoder().encode(result_all))


def read_psu():
    deviceList = [psuRRD]

    rrdPath = Get_rrdPath()

    #metrics = form.getvalue('metrics')
    rrdFile = psuRRD
    GUIdeviceList = []
    GUIdeviceList.append("PSU")
    result_all = guiDeviceResult(rrdPath, deviceList, GUIdeviceList)
    print(json.JSONEncoder().encode(result_all))


def read_temp():

    deviceList = [tempRRD]

    rrdPath = Get_rrdPath()
    #metrics = form.getvalue('metrics')
    rrdFile = tempRRD
    GUIdeviceList = []
    GUIdeviceList.append("Temperature")
    result_all = guiDeviceResult(rrdPath, deviceList, GUIdeviceList)
    print(json.JSONEncoder().encode(result_all))


def read_fan():

    deviceList = [fanRRD]

    rrdPath = Get_rrdPath()
    #metrics = form.getvalue('metrics')
    # rrdFile=tempRRD
    GUIdeviceList = []
    GUIdeviceList.append("Fan")
    result_all = guiDeviceResult(rrdPath, deviceList, GUIdeviceList)
    print(json.JSONEncoder().encode(result_all))


def read_op():

    deviceList = [opRRD]

    rrdPath = Get_rrdPath()
    #metrics = form.getvalue('metrics')
    rrdFile = tempRRD
    GUIdeviceList = []
    GUIdeviceList.append("Optical Power")
    result_all = guiDeviceResult(rrdPath, deviceList, GUIdeviceList)
    print(json.JSONEncoder().encode(result_all))

def read_disk():

    deviceList = [diskRRD]

    rrdPath = Get_rrdPath()
    #metrics = form.getvalue('metrics')
    rrdFile = tempRRD
    GUIdeviceList = []
    GUIdeviceList.append("Disk Space")
    result_all = guiDeviceResult(rrdPath, deviceList, GUIdeviceList)
    print(json.JSONEncoder().encode(result_all))

print("Content-type:text/html\r\n\r\n")


if request_Type == 'get_Metrics':
    get_Metrics(getMetricType)
elif request_Type == 'I':
    read_iDrive()
elif request_Type == 'P':
    read_psu()
elif request_Type == 'T':
    read_temp()
elif request_Type == "F":
    read_fan()
elif request_Type == "O":
    read_op()
elif request_Type == "D":
    read_disk()
