#!/usr/bin/python3

from datetime import datetime
import json
import csv
from globalSettings import *
import cgi
import cgitb
cgitb.enable()
from zipfile import ZipFile
import shutil
import os
#import datetime

form = cgi.FieldStorage()

request_Type = form.getvalue('request_Type')

startDate = form.getvalue('startDate')
endDate = form.getvalue('endDate')
maxLogLevel = form.getvalue('maxLogLevel')
logType = form.getvalue('logType')

device = DeviceName

DATE_FORMAT_LOGROUTINE = '%d/%m/%Y-%H:%M:%S'
DATE_FORMAT_FOR_GUI = '%b %d, %Y, %H:%M:%S'
def read_CCMLogs():
    displayTextList = ['Date Time', 'Element', 'Element Name',
                       'Log Level', 'State', 'Action', 'Message']
    propertyNameList = ['datetime', 'element',
                        'elementname', 'loglevel', 'sate', 'action', 'message']
    try:
        with open(LogsFilePath, 'r') as csvfile:
            filereader = csv.reader(csvfile, delimiter='@')
            i = 0
            header = []
            out_data = []
            header = propertyNameList
            for row in filereader:
                row = [elem for elem in row if elem]
                # print row
                #row[0:2] = [row[0]]
                _dict = {}
                for elem, header_elem in zip(row, header):
                    try:
                        if header_elem.strip() == "datetime":
                            elem = datetime.strptime(elem.strip(),DATE_FORMAT_LOGROUTINE).strftime(DATE_FORMAT_FOR_GUI)
                        _dict[header_elem.strip()] = elem.strip()
                    except:
                        pass
                    # _dict[header_elem.strip()] = elem.strip()
                out_data.append(_dict)
        # print datetime.strptime('15/03/2019-19:34:46', '%d/%m/%Y-%H:%M:%S')
        print(json.JSONEncoder().encode({'logsData': ApplyFilter(
            out_data), 'headers': displayTextList, 'propetyName': propertyNameList}))
    except Exception as e:
        print(json.JSONEncoder().encode({'logsData': [], 'headers': displayTextList, 'propetyName': propertyNameList}))


def read_CCMAlerts():
    displayTextList = ['Date Time', 'Element', 'Element Name',
                       'Log Level', 'State', 'Action', 'Message']
    propertyNameList = ['datetime', 'element',
                        'elementname', 'loglevel', 'sate', 'action', 'message']
    try:
        with open(AlertsFilePath, 'rb') as csvfile:
            filereader = csv.reader(csvfile, delimiter='@')
            i = 0
            header = []
            out_data = []
            header = propertyNameList
            for row in filereader:
                row = [elem for elem in row if elem]
                # print row
                #row[0:2] = [row[0]]
                _dict = {}
                for elem, header_elem in zip(row, header):
                    _dict[header_elem.strip()] = elem.strip()
                out_data.append(_dict)
        # print datetime.strptime('15/03/2019-19:34:46', '%d/%m/%Y-%H:%M:%S')
        print(json.JSONEncoder().encode({'logsData': ApplyFilter(
            out_data), 'headers': displayTextList, 'propetyName': propertyNameList}))
    except Exception as e:
        print(json.JSONEncoder().encode({'logsData': [], 'headers': displayTextList, 'propetyName': propertyNameList}))
    
    
def read_ConsoleLogs():
    displayTextList = ['Date Time', 'Message']
    propertyNameList = ['datetime','message']
    try:
        with open(ConsoleLogsPath, 'r') as csvfile:
            filereader = csv.reader(csvfile, delimiter='@')
            i = 0
            header = []
            out_data = []
            header = propertyNameList
            for row in filereader:
                row = [elem for elem in row if elem]
                # print row
                #row[0:2] = [row[0]]
                _dict = {}
                for elem, header_elem in zip(row, header):
                    try:
                        if header_elem.strip() == "datetime":
                            elem = datetime.strptime(elem.strip(),DATE_FORMAT_LOGROUTINE).strftime(DATE_FORMAT_FOR_GUI)
                        _dict[header_elem.strip()] = elem.strip()
                    except:
                        pass
                    # _dict[header_elem.strip()] = elem.strip()
                out_data.append(_dict)
        # print datetime.strptime('15/03/2019-19:34:46', '%d/%m/%Y-%H:%M:%S')
        print(json.JSONEncoder().encode({'logsData': ApplyFilter(
            out_data), 'headers': displayTextList, 'propetyName': propertyNameList}))
    except Exception as e:
        print(json.JSONEncoder().encode({'logsData': [], 'headers': displayTextList, 'propetyName': propertyNameList}))


def ApplyFilter(logs):
    if str(logType) != '':
        logTypeFilters = logType.split(",")

    if str(logType) != '' and str(logType) != 'All':
        logs = [x for x in logs if x['sate'] in logTypeFilters]

    if str(maxLogLevel) != '' and str(maxLogLevel) != 'None':
        logs = [x for x in logs if int(x['loglevel']) <= int(maxLogLevel)]

    if str(startDate) != '' and str(startDate) != 'None':
        # print datetime.strptime(str(startDate), '%m/%d/%Y')
        logs = [x for x in logs if datetime.strptime(
            x['datetime'], '%b %d, %Y, %H:%M:%S') >= datetime.strptime(str(startDate), '%Y-%m-%d')]

    if str(endDate) != '' and str(endDate) != 'None':
        # print datetime.strptime(str(endDate)+" 23:59:59", '%m/%d/%Y %H:%M:%S')
        logs = [x for x in logs if datetime.strptime(
            x['datetime'], '%b %d, %Y, %H:%M:%S') <= datetime.strptime(str(endDate)+" 23:59:59", '%Y-%m-%d %H:%M:%S')]

    return logs
def download_CCMLogs():
    try:
        zipObj = ZipFile('../LyraTL_SystemName.zip', 'w')
        with open(LogsFilePath, "r") as log_file:
            log_data = log_file.read()
        with open('LyraTL_SystemName.txt', 'w') as f:
            f.write(log_data)
        zipObj.write('LyraTL_SystemName.txt')
        zipObj.close()
        print(json.JSONEncoder().encode({'download_file':"../LyraTL_SystemName.zip", 'filename':os.path.basename("LyraTL_SystemName.zip")}))
        os.remove("LyraTL_SystemName.txt")
    except Exception as e:
        print(json.JSONEncoder().encode(({'download_file':"", 'filename':""})))

def download_ConsoleLogs():
    try:
        zipObj = ZipFile('../LyraTL_SystemName.zip', 'w')
        with open(ConsoleLogsPath, "r") as log_file:
            log_data = log_file.read()
        with open('LyraTL_SystemName.txt', 'w') as f:
            f.write(log_data)
        zipObj.write('LyraTL_SystemName.txt')
        zipObj.close()
        print(json.JSONEncoder().encode({'download_file':"../LyraTL_SystemName.zip", 'filename':os.path.basename("LyraTL_SystemName.zip")}))
        os.remove("LyraTL_SystemName.txt")
    except Exception as e:
        print(json.JSONEncoder().encode(({'download_file':"", 'filename':""})))

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

if request_Type == 'read_CCMLogs':
    read_CCMLogs()
elif request_Type == 'read_CCMAlerts':
    read_CCMAlerts()
elif request_Type == 'read_ConsoleLogs':
    read_ConsoleLogs()
elif request_Type == 'download_CCMLogs':
    download_CCMLogs()
elif request_Type == 'download_ConsoleLogs':
    download_ConsoleLogs()
