from ...Dependencies.Utilities.util import *
from ...Dependencies.MongoConnection.mongoConnect import *
from ...Dependencies.SmtpMail.SendMail import *
import random


notes = Blueprint('notes',__name__)


@notes.route("/testNotes")
def testNotes():
    return "This is for testing the Notes"

@notes.route("/notesTable/<string:cloudname>",methods = ["POST","GET"])
def notesTable(cloudname):
    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"))
    print("The CloudName is : ")
    print(cloudname)

    pipeline = [
        {"$match": {"cloudName": cloudname}},
        {"$group": {"_id": "$unique_id", "count": {"$sum": 1}, "latestDoc": {"$max": "$$ROOT"}}}
    ]

    unique_docs_with_counts = list(opcenterNotes.aggregate(pipeline))
    print(unique_docs_with_counts)

    listNotes = []
    
    for group in unique_docs_with_counts:
        modified = False
        unique_id = group['_id']
        count = group['count']
        timestamp = group['latestDoc']["timestamp"]
        dt_object = datetime.fromtimestamp(timestamp)
        formatted_datetime = dt_object.strftime("%d-%b-%y %I:%M %p")
        group['latestDoc']["dateTime"] = formatted_datetime
        if count > 1:
            modified = True
        group['latestDoc']["modified"] = modified
        listNotes.append(group.get("latestDoc"))
        print(f"Unique ID: {unique_id}, Document Count: {count}")

    # listNotes.sort(key=lambda x: datetime.strptime(x['latestDoc']['dateTime'], "%d-%b-%y %I:%M %p"), reverse=True)
    print(listNotes)
    return render_template("dashboard/notesPage.html",opcenterData = listNotes,cloudname = cloudname)



@notes.route("/editNotes",methods = ["POST","GET"])
def editNotes():
    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':
        id = request.form['id']
        cloudname = request.form['cloudname']
        print(id)
        object_id = ObjectId(id)
        opcenterData = opcenterNotes.find_one({"_id":object_id})
        print(opcenterData)
        notesContent = opcenterData.get("content")
        notesUniqueId = opcenterData.get("unique_id")
        print(notesContent)
    return jsonify({'htmlresponse': render_template('dashboard/notesedit.html',notesContent = notesContent,object_id=object_id,cloudname =cloudname,notesUniqueId = notesUniqueId)})



@notes.route("/addNotes",methods = ["POST","GET"])
def addNotes():
    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':
        userid = request.form['userid']
        print("This is notesTable") 
        print(userid)       
    return jsonify({'htmlresponse': render_template('dashboard/stickyNotes.html',userid = userid)})


@notes.route("/addContent",methods=["POST"])
def addContent():

    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':
        content = request.form['content']
        cloudName = request.form['cloudName']
        current_date = datetime.now()
        timestamp = current_date.timestamp()
        author = session['username']
        unique_id = int(timestamp) + random.randint(0,1000)

        collection = {
            "unique_id":unique_id,
            "content" : content,
            "timestamp" : timestamp,
            "author" : author,
            "cloudName" : cloudName
        }
        result = opcenterNotes.insert_one(collection)
        # inserted_id = result.inserted_id
        # CloudName.update_one(
        #     {"CloudName": clouDNaMe},
        #     {"$addToSet": {"notesid": inserted_id}}
        # )
        print("Successfully inserted")

    return redirect(url_for('notes.notesTable',cloudname=cloudName))


@notes.route("/editContent",methods=["POST"])
def editContent():

    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':
        content = request.form['content']
        notesUniqueId = request.form['notesUniqueId']

        print("The above is the notes unique id mentioned")
        print(notesUniqueId)
        cloudname = request.form['cloudname']
        print(cloudname)
        print("=======================================THE ABOVE IS THE CLOUD NAME=================================")
        current_date = datetime.now()
        timestamp = current_date.timestamp()
        author = session['username']
        collection = {
            "unique_id":int(notesUniqueId),
            "content" : content,
            "timestamp" : timestamp,
            "author" : author,
            "cloudName" : cloudname
        }

        print("The route was here")
        result = opcenterNotes.insert_one(collection)
        print("Successfully inserted")
    return redirect(url_for('notes.notesTable',cloudname=cloudname))


@notes.route("/notesTest")
def notesTest():

    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"))

    cloudDetails = CloudName.find_one({"CloudName":"ceat"}, sort=[('_id', pymongo.DESCENDING)])
    notesId = cloudDetails.get("notesid")
    listNotes = []
    if notesId is not None:
        for noteid in notesId:
            object_id = ObjectId(noteid)
            opcenterData = opcenterNotes.find_one({"_id":object_id})
            listNotes.append(opcenterData)

    # listNotes.reverse()
    return render_template("dashboard/notesPage.html",opcenterData = listNotes)



@notes.route("/writeNotes",methods=["POST"])
def writeNotes():
    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['cloudname']
        print(cloudname)
        print("The above is the cloudname")
    return jsonify({'htmlresponse': render_template('dashboard/notesadd.html',cloudname = cloudname)})



@notes.route("/modified",methods=["POST"])
def modified():
    if request.method == 'POST':
        print("====================================================================================================")
        id = int(request.form['id'])
        cloudname = request.form['cloudname']
        newid = ObjectId(request.form['newid'])

        print("The original object id is")
        print(newid)        
        print("The value of the id is ")
        print(id)

        print("The value of the cloudName")
        print(cloudname)

        result = opcenterNotes.find({"cloudName": cloudname, "unique_id": id})
    
        newList = []
        for group in result:
            if group["_id"] != newid: 
                timestamp = group["timestamp"]
                dt_object = datetime.fromtimestamp(timestamp)
                formatted_datetime = dt_object.strftime("%d-%b-%y %I:%M %p")
                group["dateTime"] = formatted_datetime
                newList.append(group)

    return jsonify({'htmlresponse': render_template('dashboard/oldNotes.html',oldNotesList = newList)})