#!/usr/bin/python3
import datetime
import json
import cgi
import sqlite3
from db import *
from globalSettings import *
from global_func import *
form = cgi.FieldStorage()
from clearTextPwd import *
request_Type = form.getvalue('requestType')
conn = sqlite3.connect(DBPath)
conn.text_factory = str
c = conn.cursor()
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import zipfile
import csv
def send_email():

    query = c.execute(
        "select name,state,level,user,pw,out_server,in_server,authentication,smtp_server,port_number,alert_msg,id from email")
    global logType  
    fetched_data = c.fetchall()
    if fetched_data:
        for col in fetched_data:
            name = col[0]
            state = col[1]  # form.getvalue("state")
            logType = col[2]
            user = col[3]
            password = (col[4])
            out_server = col[5]
            in_server = col[6]
            authentication = col[7]
            smtp_server = col[8]
            port_number = col[9]
            alert_msg = col[10]
    else:
        print(json.JSONEncoder().encode({"status" : 400, "response" : "Please check the Email configuration !!"}))
        return False

    sender_email = in_server
    receiver_email = out_server
    subject = 'Logs Files'
    message = 'This is a test email.'

    # Create a MIME message
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    # msg.attach(MIMEText(message, 'plain'))
    # SMTP server settings
    smtp_server = smtp_server
    smtp_port = port_number
    smtp_username = sender_email
    smtp_password = password
    

    displayTextList = ['Date Time', 'Element', 'Element Name',
                       'Log Level', 'State', 'Action', 'Message']
    propertyNameList = ['datetime', 'element',
                        'elementname', 'loglevel', 'sate', 'action', 'message']
    
    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]
            _dict = {}
            for elem, header_elem in zip(row, header):
                _dict[header_elem.strip()] = elem.strip()
            out_data.append(_dict)
    if(len(out_data) == 0):
        print(json.JSONEncoder().encode({"status" : 200, "response" : "Logs Not Available!"}))
        return False
    filterData = ApplyFilter(out_data)
    zipObj = zipfile.ZipFile('../AdoptionELS_SystemName.zip', 'w')
    with open('ccmlog.txt', 'w') as file:
        for item in filterData:
            file.write(str(item) + '\n')
    zipObj.write('ccmlog.txt')
    zipObj.close()
    with open("../AdoptionELS_SystemName.zip",'rb') as file:
    # Attach the file with filename to the email
        msg.attach(MIMEApplication(file.read(), Name='Logs_SystemId.zip'))

    # Create an SMTP session
    try:
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            # Enable TLS encryption
            server.starttls()
            # Login to the SMTP server
            server.login(smtp_username, smtp_password)
            # Send the email
            server.send_message(msg)
            server.quit()
        # print("Email sent")
            if CCM:
                cmd = "send_logs"
                cmd_id = get_ccm_command_id()
                name = "send_logs"
                message = "set,element=send_logs,args=9,uuid={0},action={1},element_name={2},device={3}".format(cmd_id, cmd, name,device)
                send_ccm_msg(message)
                response = get_ccm_response(cmd_id)
                delete_ccm_response(cmd_id)
                jsonSchema = {"status" : 200, "response" : "Logs Sent Successfully!"}
                print(json.JSONEncoder().encode(jsonSchema))
            else:
                jsonSchema = {"status" : 200, "response" : "Logs Sent Successfully!"}
                print(json.JSONEncoder().encode(jsonSchema))
    except smtplib.SMTPException as e:
        jsonSchema = {"status" : 'fail', "response" : "Please check the Email configuration !!"}
        print(json.JSONEncoder().encode(jsonSchema))
    except Exception as e:
        jsonSchema = {"status" : 'fail', "response" : "Log Not Sent!"}
        print(json.JSONEncoder().encode(jsonSchema))
    
def checkEmail():
    query = c.execute(
        "select name,state,level,user,pw,out_server,in_server,authentication,smtp_server,port_number,alert_msg,id from email")
    global logType  
    fetched_data = c.fetchall()
    if fetched_data:
        for col in fetched_data:
            name = col[0]
            state = col[1]  # form.getvalue("state")
            logType = col[2]
            user = col[3]
            password = (col[4])
            out_server = col[5]
            in_server = col[6]
            authentication = col[7]
            smtp_server = col[8]
            port_number = col[9]
            alert_msg = col[10]
    else:
        print(json.JSONEncoder().encode({"status" : 400, "response" : "Please check the Email configuration !!"}))
        return False
    
    print(json.JSONEncoder().encode({"status" : 200, "response" : "Success"}))
    return True

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]
    

    return logs

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

cmd_Id = get_ccm_command_id()
if request_Type == 'selfTest':
    if CCM:
        cmd="test_response"
        name="self_start"
        action="start"
        message="set,element=self_start,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)
        print(response)
    else:
        jsonSchema = {"status" : 200, "response" : "Default Value Reset Successfully"}
        print(json.JSONEncoder().encode(jsonSchema))
if request_Type == 'remoteDiag':
    if CCM:
        cmd="test_response"
        name="remote_diagnostic"
        action="start"
        message="set,element=remote_diagnostic,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)
        print(response)
    else:
        jsonSchema = {"status" : 200, "response" : "Default Value Reset Successfully"}
        print(json.JSONEncoder().encode(jsonSchema))
if request_Type == 'openManual':
    if CCM:
        cmd="test_response"
        name="open_manual"
        action="start"
        message="set,element=open_manual,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)
        print(response)
    else:
        jsonSchema = {"status" : 200, "response" : "Default Value Reset Successfully"}
        print(json.JSONEncoder().encode(jsonSchema))
if request_Type == 'apiCommand':
    if CCM:
        cmd="test_response"
        name="open_api"
        action="start"
        message="set,element=open_api,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)
        print(response)
    else:
        jsonSchema = {"status" : 200, "response" : "Default Value Reset Successfully"}
        print(json.JSONEncoder().encode(jsonSchema))
if request_Type == 'logs':
    send_email()

if request_Type == "remoteDiagSend":
    checkEmail()