import pyodbc
import datetime
import logging
import logging.handlers as handlers
from logging.handlers import RotatingFileHandler,SysLogHandler
import config
import threading
import time
from cryptography.fernet import Fernet
import tfacecompare

logging.basicConfig(
    handlers=[
        RotatingFileHandler("TFaceCompare.log", maxBytes=10485760, backupCount=10),
        SysLogHandler(address=('3.18.67.18',514))
    ],
    level=logging.DEBUG,
    format='"%(asctime)s -[TFaceCompare] - %(levelname)-7.7s %(message)s',
    datefmt="%Y-%m-%d %H:%M:%S",
)
if config.is_encrypted_password:
    key = config.cipher_key
    cipher_suite = Fernet(key)
    password = cipher_suite.decrypt(config.password)
    password = password.decode("utf-8")
else:
    password = config.password

server = config.server
database = config.database
username = config.username
password = config.password


def save_faceauth_data(
    request_date,
    response_date,
    image1_path,
    image2_path,
    originator,
    agentId,
    result,
    resultReason,
    score,
    confidence,
):
    """
    This function inserts the data to the SQL server which has the details of face comparasion
    INPUT: request_date,response_date,originator,image1_path,image2_path,result,result_reason,score,confidence
    OUTPUT:
    """
    try:
        cnxn = pyodbc.connect(
            "DRIVER={ODBC Driver 13 for SQL Server};SERVER="
            + server
            + ";DATABASE="
            + database
            + ";UID="
            + username
            + ";PWD="
            + password
        )

        cursor = cnxn.cursor()
        logging.info(
            agentId
            + ":save_faceauth_data: requestDate: "
            + str(request_date)
            + ", responseDate: "
            + str(response_date)
            + ", Originator: "
            + str(originator)
            + ", Image Path1: "
            + str(image1_path)
            + ", Image Path2: "
            + str(image2_path)
        )

        cursor.execute(
            """
        INSERT INTO FaceAuth_Transactions (RequestDateTime, ResponseDateTime, Originator, Image1Path, Image2Path, Result, ResultReason, Score, Confidence) 
        VALUES (?,?,?,?,?,?,?,?,?)""",
            request_date,
            response_date,
            originator,
            image1_path,
            image2_path,
            result,
            resultReason,
            score,
            confidence,
        )
        cnxn.commit()
        logging.info(agentId + ":Successfully inserted data to the table")
        cursor.close()
        cnxn.close()
        return

    except Exception as ex:
        logging.info(
            agentId + ":Exception in inserting data to the sql table " + str(ex)
        )
        return

def insert_agent_details(userName,firstName,lastName,profilepic):
    try:
        logging.info("insert_agent_details")
        cnxn = pyodbc.connect(
            "DRIVER={ODBC Driver 17 for SQL Server};SERVER="
            + server
            + ";DATABASE="
            + database
            + ";UID="
            + username
            + ";PWD="
            + password
        )

        cursor = cnxn.cursor()
        cursor.fast_executemany = True

        feature = [('IsCRMEnabled',0),('IsFaxInternationalEnabled',0),('IsFaxOutEnabled',0),('IsFaxPrintEnabled',0),
        ('IsHoldVoiceCallOnChatCall',0),('IsManualInEnabled',0),('IsSecondTextChatAutoAnswer',0),('IsSMSOutEnabled',0),('IsTextChatAutoACWEnabled',0),
        ('IsTextChatAutoAnswer',0),('IsVoiceACDAutoACWEnabled',0),('IsVoiceACDAutoAnswerEnabled',0),('IsVoiceAllAutoACWEnabled',0)
        ,('IsCameraCaptureEnabled',1),('IsFaceAuthenticationEnabled',1),('IsFaceCountCheckEnabled',0),('IsFaceTouchMonitorEnabled',0),
        ('IsLocationEnabled',0),('IsScreenCaptureEnabled',0),('IsTcisConnectionEnabled',0)]

        for row in range(len(feature)):
            feature[row] = feature[row] + (userName,)

        cursor.executemany("insert into AGT_AgentFeature(Feature,Enable,AgentId) values (?, ?, ?)", feature)
        
        cursor.execute(
            """
        INSERT INTO AGT_Agent (UserName, FirstName, LastName, AvayaLoginID, Profile, TeamID, PrimarySupervisorID, LastLoginDate, LastLoginTime,CreatedDate,CreatedTime,CreatedBy) 
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",
            userName,
            firstName,
            lastName,
            userName,
            "A",
            1,
            1,
            "",
            "",
            "",
            "",
            "user"
        )
        cnxn.commit()
        cursor.close()

        cursor1 = cnxn.cursor() 

        cursor1.execute(
            """
        INSERT INTO AGT_Agent_Profile (AgentId, Voice, Email, SMS, TextChat, VideoChat, Role, ProfilePicture) 
        VALUES (?,?,?,?,?,?,?,?)""",
            userName,
            1,
            1,
            1,
            1,
            1,
            "Maker",
            "",
        )
        
        cnxn.commit()
        cursor1.close()
        cnxn.close()
        return "Success"

    except Exception as identifier:
        logging.info("Exception")
        return "Failure"
