#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 15:19:04 2019

@author: dark
"""
import os
from flask import Flask,render_template,request
from multiprocessing import Process,freeze_support
import cv2
import datetime
import time
from Mongodb_SendingString import UploadImage

app1 = Flask('__name__')

@app1.route('/',methods=['GET','POST'])
def index():
    return render_template("this.html")

@app1.route('/start',methods=['GET','POST'])
def start(): 
    
    userid=None
    password=None
    userid=request.form.get('username')
    password=request.form.get('password')
    print(str(userid)+"\n"+str(password))
    if  password=='1234' and userid=="1@gmail.com":
        return render_template("parallax.html")
    else:
        return "Error occured"
    
@app1.route('/py',methods=['GET','POST'])
def py():     

     p1 = Process(target=detect_faces)
     p2 = Process(target=upload_images)
        
     p1.start()
     p2.start()
     
     return render_template("parallax_2.html")
 
def detect_faces():

    face_cascade = cv2.CascadeClassifier('/home/dark/Documents/haarcascades/haarcascade_frontalface_default.xml')
    
    
    cap = cv2.VideoCapture(0)
    path ='/home/dark/Programing/Major/Images'
    imgCtr=0
    
    
    
    while 1:
        ret, img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
        for (x,y,w,h) in faces:
            
    #=============== Image Naming ===================================
    
            sysTime = datetime.datetime.now()
            deviceTime=sysTime.strftime("%d_%m_%Y_%H_%M_%S_%f")
            imageName = "Cam1_"+deviceTime+".png"
            
    #=============== Image Naming block complete ====================
            
            cv2.rectangle(img,(x,y),(x+w,y+h),(57,255,20),2)
            #roi_gray = gray[y:y+h, x:x+w]
            #roi_color = img[y:y+h, x:x+w]
            
            sub_face = img[y:y+h, x:x+w]
            imgCtr+=1
            
            if(imgCtr==5):
                cv2.imwrite(os.path.join(path , imageName), sub_face)
                imgCtr=0    
                
        cv2.imshow('Press ESC to exit',img)
        k = cv2.waitKey(30) & 0xff
        if k == 27:
            break
    
    cap.release()
    cv2.destroyAllWindows()


def upload_images():
           
        obj = UploadImage()
        starttime=time.time()
        try: 
            while True:    
                obj.upload()
                time.sleep(60.0 -((time.time() - starttime) % 60.0)) 
        except KeyboardInterrupt:
            pass    
 
if __name__=='__main__':
    freeze_support()
    app1.run(host='0.0.0.0')
    
