def viz_marks():
    if request.method == 'POST':
        conn = MysqlConnector()
        usn = request.form.get('usn')
        ia = request.form.get('ia')
        assign = request.form.get('assign')
        sub = request.form.get('sub')
        sub_name = conn.select(columnName='sub_name', tableName='semesters', where=f"sub_id='{sub}' ")
        # print(sub_name)
        marks=[]
        labels=['Assignment','Internal Assessment','Lab','Project']
        if usn and ia and assign and sub:
            res = conn.select(columnName='marks',tableName='assignment_marks',where=f" sub_id='{sub}' and usn='{usn}' and assignment_id='{assign}'")
            if res:
                marks.append(res[0][0])
            res1 = conn.select(columnName='distinct(marks)',tableName='ia_marks',where=f"sub_id='{sub}' and usn='{usn}' and ia_no='{ia}' ")
            if res1:
                marks.append(res1[0][0])
            res2 = conn.select(columnName='marks',tableName='lab_marks',where=f"sub_id='{sub}' and usn='{usn}'")
            if res2:
               marks.append(res2[0][0])
            res3 = conn.select(columnName='marks',tableName='project_marks',where=f"sub_id='{sub}' and usn='{usn}'")
            if res3:
               marks.append(res3[0][0])
            conn.closeConnection()
            return render_template('viz/marks.html',values=marks, labels=labels,sub_name=sub_name)
    return render_template('viz/marks.html')
def lab():
    if request.method == "POST":
        logging.info(" POST request")
        usn = request.form.get("usn")
        sub_id = request.form.get("sub_id")
        lab_marks = request.form.get("lab_marks")
        where = f'usn = {usn}'
        conn = MysqlConnector()
        res=conn.select(tableName='students',columnName='usn',where=where)
        if res:
            conn.insert(
                execute=True,
                tableName="lab_marks",
                column={
                    "usn": usn,
                    "marks": lab_marks,
                    "sub_id":sub_id
                }
            )
            res = conn.select(columnName="*", tableName="students")
            conn.closeConnection()
            logging.info(f" Results after commit: {res}")
            logging.info(" Data received. Now redirecting ...")
            flash('Upload successful!','success')
            return redirect(url_for('lab'))
        else:
            logging.critical("Aborting upload as primary key (usn) doesn't exist in tables student ")
            flash('Upload failed! This usn is not registered, make sure student register first.','danger')
            return redirect(url_for('lab'))
    else:
        return render_template("upload/lab.html")
def form():
    print("Running /form from", request.remote_addr)

    if request.method == "POST":
        logging.info(" POST request")
        img_b64_list = request.form.get("canvas")
        usn = request.form.get("usn")
        fname = request.form.get("fname")
        lname = request.form.get("lname")
        email = request.form.get("email")
        phone_no = request.form.get("phone_no")
        semester = request.form.get("semester")
        branch = request.form.get("branch")
       
        logging.info(f' Received image set length: {len(img_b64_list)}')

        
        np_img = decode(img_data=img_b64_list)
        rgb_image = np_img[:, :, ::-1] 
        pathName=f"./images/{branch.split(' ')[0]}/{semester}"
        
        if not os.path.exists(pathName):
            os.makedirs(pathName)
        os.chdir(pathName)
        cv2.imwrite(f'{usn}.jpg',np_img)
        os.chdir('../../../')

        conn=MysqlConnector()
        res=conn.insert(
            execute=True,
            tableName="students",
            column={
                "usn": '"'+usn+'"',
                "fname": '"'+fname+'"',
                "lname": '"'+lname+'"',
                "email": '"'+email+'"',
                "phone_no": '"'+phone_no+'"',
                "sem": '"'+semester+'"',
                "branch": '"'+branch.split(" ")[0]+'"',
                "status":"NULL"
            },
        )
        res = conn.select(columnName="*", tableName="students")
        conn.closeConnection()
        logging.info(f" Results after commit: {res}")
        logging.info(" Data received. Now redirecting ...")

        return redirect("form")
        # else:
            # logging.critical(f' Loaded json is: {type(json_str_img_list)}, storage skipped')
    else:
        return render_template("form1.html")
def get_5_last_entries():
    answers_to_send = {}
    conn = MysqlConnector()
    cols = ['usn','name','login','logout', 'sem']
    last_entries = conn.select(columnName = ['distinct(attendance.usn)','fname', 'login_' ,'logout','sem'] , tableName = ['attendance','students'], where='attendance.usn=students.usn' ,orderBy = 'usn DESC LIMIT 5')
    
    #{0: {'usn': '', 'name': '', 'login': '', 'logout': ''}, 1: {'usn': '', 'name': '', 'login': '','logout': ''}, 2: {...}, ...}
    if last_entries:         
        for index,person in enumerate(last_entries):
                answers_to_send[index] = {}
                for i,j in zip(cols,person):
                    answers_to_send[index][i] = str(j)
    else:
        answers_to_send = {'error': 'DB is not connected or empty'}
    if conn:
        conn.closeConnection()
    return answers_to_send
def attendance():
    
    if request.method == 'POST':
        conn = MysqlConnector()
        entries={}
        json_data = request.get_json()
        # print(json_data)
        usn_present_today = conn.select(columnName=['attendance.usn','students.fname'] , tableName=['attendance', 'students'], where=f" students.usn = '{json_data['usn']}' AND attendance.date_ = '{json_data['date']}' ")

        if usn_present_today:
            update_usn = conn.update(execute=True, tableName='attendance', column={'logout': 'now()' }, where = f"usn = '{json_data['usn']}'")
        else:
            insert_usn = conn.insert(execute=True, tableName='attendance', column={'usn': f" '{json_data['usn']}' ", 'date_': f" '{json_data['date']}' ", 'login_': 'now()' })
            
        logging.debug(entries)
        conn.closeConnection()
    entries = get_5_last_entries()
    print(entries)
        #return details along
    return render_template("video_feed.html", entry=entries)
def viz_attendance():
    if request.method == 'POST':
        branch = request.form.get("branch")
        sem = request.form.get("semester") 
        spec_date = request.form.get("date")
        usn = request.form.get("usn")
        
        conn = MysqlConnector()
        
        res = conn.select(columnName=['date_','count(distinct(attendance.usn))'], tableName=['attendance','students'], where=f"login_ is not null and branch='{branch.split(' ')[0]}' and sem='{sem}' ", groupBy='date_')
        
        date=[]
        count=[]
        for i in res:
            date.append(i[0])
            count.append(i[1])
       
        # json_data = json.dumps(
        #     {
        #         "date" : date.__str__(),
        #         "count" : count
        #     }
        # )
        if spec_date and usn:
            
            entries = conn.select(columnName='*', tableName='attendance', where= f"date_ = '{spec_date}' and usn='{usn}'") 
            d={}   
            usn=[]
            login=[]
            logout=[]
            date=[]
            sub_id=[]
            for i in entries:
                usn.append(i[0])
                login.append(i[1])
                logout.append(i[2])
                date.append(i[3])
                sub_id.append(i[4])
            
            d={
                'usn':usn,
                'login':login,
                'logout':logout,
                'date':date,
                'sub_id':sub_id
            }    
            return render_template('viz/attendance.html',values=count,labels=date,spec_date=spec_date,entries=d) 
            
        elif spec_date:    
            
            d={}
            entries = conn.select(columnName='*', tableName='attendance', where= f"date_ = '{spec_date}'")    
            usn=[]
            login=[]
            logout=[]
            date=[]
            sub_id=[]
            for i in entries:
                usn.append(i[0])
                login.append(i[1])
                logout.append(i[2])
                date.append(i[3])
                sub_id.append(i[4])
            
            d={
                'usn':usn,
                'login':login,
                'logout':logout,
                'date':date,
                'sub_id':sub_id
            } 
            conn.closeConnection()
            return render_template('viz/attendance.html',values=count,labels=date,spec_date=spec_date,entries=d) 
        
            
        return render_template('viz/attendance.html',values=count,labels=date,spec_date=spec_date) 
        
            
    # jsonify({'payload':json_data})
    return render_template('viz/attendance.html')