from ...Dependencies.Utilities.util import *
from ...Dependencies.MongoConnection.mongoConnect import *
from ...Dependencies.SSLConfig.sslInfo  import *
from ..variables import *
import time
from datetime import datetime

smtp_server = 'email-smtp.us-east-2.amazonaws.com'
smtp_port = 587
sender_email = 'no-reply@parablu.com'
subject = 'Welcome to Opcenter'

agentCreate = Blueprint('agentCreate',__name__)


@agentCreate.route("/createAgent",methods = ["POST","GET"])
def createAgent():
    if not session.get('logged_in'):
        flash("Sorry!!! You have not logged in","warning")
        return redirect(url_for('authentication_blueprint.login'))
    
    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))
        
    if request.method == 'POST':
        cloudname = request.form['clientCloudName']
        primaryFqdn = request.form['primaryFqdn']
        agentType = request.form['agentType']
        logintype = request.form['logintype']
        proxytype = request.form['proxytype']
        IpSettings = request.form['IpSettings']
        installType = request.form['installType']
        agentversion = request.form['agentversion']

        submittedBy = session['username']
        
        current_date = datetime.now()
        current_timestamp_millis = current_date.timestamp()

        agentDetails = {
            "cloudName" : cloudname,
            "primaryFqdn" : primaryFqdn,
            "agentType" : agentType,
            "agentversion": agentversion,
            "logintype" : logintype,
            "proxytype" : proxytype,
            "IpSettings":IpSettings,
            "installType":installType,
            "SubmittedBy" : submittedBy,
            "timestamp": current_timestamp_millis,
            "agentcreatedTime": None,
            "agentcreatedBy":None,
            "agentstatus": "Approval Pending",
            "approval":False,
            "approvedBy":None
        }
        resultId = MongoCollectionInstance.setMacAgentRequest(agentDetails)
        #Mail Should be triggered
        if resultId is not None: 
            sendApprovalMail(resultId,cloudname,agentType,agentversion)
            return redirect(url_for('agentCreate.agentstatus', result_id=resultId))
        else:
            return "Failed to requested the Agent"
    return render_template("/dashboard/agentCreate.html")

@agentCreate.route("/agentStatus/<result_id>")
def agentstatus(result_id):
    if not session.get('logged_in'):
        flash("Sorry!!! You have not logged in","warning")
        return redirect(url_for('authentication_blueprint.login'))
    
    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    fileList = {}
    print(".......This is the agent created id")
    agentDetails = MongoCollectionInstance.getAgentDetails(result_id)
    agentStatus = agentDetails.get("agentstatus")
    agentName = agentDetails.get("cloudName")
    agentVersion = agentDetails.get("agentversion")
    agentRequestTime = agentDetails.get("timestamp")
    agentDeliveredOn = agentDetails.get("agentcreatedTime")
    agentFqdn = agentDetails.get("primaryFqdn")
    approvedBy = agentDetails.get("approvedBy")
    approvedOn = agentDetails.get("approvedOn")

    if approvedBy is None or approvedOn is None:
        approvedBy = "Not Yet Approved"
        approvedOn = "Not Yet Approved"
    try:
        Totalfile = agentDetails.get("agentLinks")
        dmgfile = Totalfile.get("Parablu_EPA.dmg")
        pkgFile = Totalfile.get("Parablu_EPA.pkg")
        updateFile = Totalfile.get("update.xml")
        parablZip = Totalfile.get("Parablu_EPA.zip")


    except Exception as e:
        dmgfile = "N/A"
        pkgFile = "N/A"
        updateFile = "N/A"
        parablZip = "N/A"

    
    return render_template("/dashboard/agentStatus.html",approvedBy = approvedBy,approvedOn = approvedOn,dmgfile = dmgfile,updateFile = updateFile,parablZip = parablZip,pkgFile=pkgFile,agentFqdn = agentFqdn,fileList = fileList,agentDeliveredOn = agentDeliveredOn,agentStatus = agentStatus,agentName = agentName,agentVersion = agentVersion,agentRequestTime = agentRequestTime)


def sendApprovalMail(agentTicketId,cloudname,agentType,agentversion):
    print("..........agent ticket id is ")
    senderEmailList = MongoCollectionInstance.getSuperAdminList()
    # message = MIMEMultipart()
    message = MIMEMultipart()
    message['From'] = sender_email
    message['Subject'] = "There's a request for Agent Creation"
    # body = "Congratulations!!! You are successfully added to Opcenter Team. Kindly Save your email: password:  (Very Confidential)"
    url_link = url_for('agentCreate.approveAgent',result_id = agentTicketId, _external=True)
    for emaillist in senderEmailList:
        message['To'] = emaillist
        html = render_template('dashboard/AgentAproval.html',cloudname = cloudname,agentType=agentType,agentversion=agentversion ,url_link=url_link)
        message.attach(MIMEText(html, 'html'))
        smtp_session = smtplib.SMTP(smtp_server, smtp_port)
        smtp_session.starttls()
        smtp_session.login('AKIAVZLS53X5PBNLV5GJ', 'BLPn8AcrtZTJz+BdyyTCccNQqj6UxIB/kvKMv9AWd/mB')
        smtp_session.sendmail(sender_email, emaillist, message.as_string())
        smtp_session.quit()
    return "This is approval mail"


@agentCreate.route("/approveAgent/<result_id>")
def approveAgent(result_id):
    if not session.get('logged_in'):
        flash("Sorry!!! You have not logged in","warning")
        return redirect(url_for('authentication_blueprint.login'))
    
    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    if not session.get('logged_in'):
        flash("Sorry!!! You have not logged in","warning")
        session['result_id'] = result_id
        return redirect(url_for('authentication_blueprint.login'))
    
    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                session['result_id'] = result_id
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            session['result_id'] = result_id
            return redirect(url_for("authentication_blueprint.login"))

    print(result_id)
    print("........the above it the document ID")
    current_timestamp_millis = int(time.time() * 1000)
    agentCreatedBy = session['username']
    
    agentDetails = MongoCollectionInstance.updateAgentDetails(result_id,agentCreatedBy,current_timestamp_millis)
    agentDetailsInJson = MongoCollectionInstance.getAgentDetails(result_id)
    
    agentData = {
        "cloudName" : agentDetailsInJson.get("cloudName"),
        "primaryFqdn" : agentDetailsInJson.get("primaryFqdn"),
        "agentType" : agentDetailsInJson.get("agentType"),
        "agentversion" : agentDetailsInJson.get("agentversion"),
        "logintype" : agentDetailsInJson.get("logintype"),
        "proxytype" : agentDetailsInJson.get("proxytype"),
        "IpSettings" : agentDetailsInJson.get("IpSettings"),
        "installType" : agentDetailsInJson.get("installType")
    }

    file_name = "C:\\Office_Poorna\\OpcenterV3\\AgentData.json"
    with open(file_name, 'w') as json_file:
        json.dump(agentData, json_file)

    if agentDetails:
        message = MIMEMultipart()
        message['From'] = sender_email
        message['Subject'] = subject
        with open(file_name, 'rb') as attachment:
            part = MIMEApplication(attachment.read(), Name=file_name)
        part['Content-Disposition'] = f'attachment; filename="{file_name}"'
        message.attach(part)
        # Add a text message (optional)
        text = "Here is the JSON data you requested."
        message.attach(MIMEText(text, 'plain'))
        smtp_session = smtplib.SMTP(smtp_server, smtp_port)
        smtp_session.starttls()
        smtp_session.login('AKIAVZLS53X5PBNLV5GJ', 'BLPn8AcrtZTJz+BdyyTCccNQqj6UxIB/kvKMv9AWd/mB')
        smtp_session.sendmail(sender_email, "poornachandra@parablu.com", message.as_string())
        smtp_session.quit()
        return redirect(url_for("agentCreate.agentstatus",result_id = result_id))
    return "Check this again"


@agentCreate.route("/getAllApprovedList",methods=["GET"])
def getAllApprovedList():
    print("This is the get request for getting all the approved list")
    agentApproved = MongoCollectionInstance.getApprovedDetails()
    print(agentApproved)
    return agentApproved


@agentCreate.route("/setMacAgentLinks",methods=["POST"])
def setMacAgentLinks():
    data = request.json 
    try:
        agentCreationId = data.get("agentTicketId")
        agentCreatedBy = data.get("agentCreatedBy")
        current_date = datetime.now()
        current_timestamp_millis = current_date.timestamp()
        agentLinks = data.get("agentLinks")
        agentApproved = MongoCollectionInstance.updateAgentCreatedDetails(agentCreationId,agentCreatedBy,current_timestamp_millis,agentLinks)
        if(agentApproved):

            print("Successfully Updated the Agent Links")
        else:
            print("Failed in updating the agent links")

    except Exception as e:
        print("Failed")
    return "Successfully posted"


@agentCreate.route("/listAgentRequestDetails")
def listAgentRequests():
    agentList = MongoCollectionInstance.getAllAgentRequest()
    print(agentList)
    return render_template("/dashboard/agentTicket.html",agentList = agentList)
