from run import app
from flask_restful import Resource, reqparse
from werkzeug import datastructures
import datetime
import time
import cv2
import pytz
import os
import facenet_predict
import face_cascade
import svm_classification
import train
from influxdb import InfluxDBClient
import pymysql

class Whois(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('file',type=datastructures.FileStorage, location='files',required=True,help="Please slecet a image which incloud car to upload.")
        
    @staticmethod
    def save(self):
        save_time=time.time()
        dt = datetime.datetime.now(pytz.timezone('Asia/Taipei'))
        dt = dt.strftime('%Y_%m_%d_%H_%M_%S_%f')+'.jpg'
        filepath = os.path.abspath(os.path.join(app.config['UPLOAD_FOLDER'], dt))
        args =self.reqparse.parse_args()
        args['file'].save(filepath)
        return save_time,filepath
    
    def get(self):
        return "hello world"
    
    def post(self):
        save_time,img_path = self.save(self)
#         print(img_path)
        img=cv2.imread(img_path)
        faces=face_cascade.get_face(img)
        if(len(faces)!=2):
            return {'error':faces}
        embs=facenet_predict.calc_embs(faces[1])
        result=svm_classification.result(embs)
        return {'time':save_time,'face_location':str(faces[0]),'name':result[0],'confidence':result[1]}

#         if(len(result)!=3):
#             return {'error':result}
#         return {'face':str(result[0]),'name':result[1],'confidence':result[2]}
#         result=train.get_result(img_path)
#         return {'message':str(result)}

    
        
    
class Upload_image(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('name',required=True,help="Please write down your name and we will save your image to folder of train")
        self.reqparse.add_argument('file',type=datastructures.FileStorage, location='files',required=True,help="Please slecet a image which incloud car to upload.")
    @staticmethod
    def save(self):
        dt = datetime.datetime.now(pytz.timezone('Asia/Taipei'))
        dt = dt.strftime('%Y_%m_%d_%H_%M_%S_%f')+'.jpg'
        args =self.reqparse.parse_args()
        fileroot=os.path.abspath(os.path.join('./nas/Face/train',args['name']))
        filepath = os.path.join(fileroot,dt)
        if(not os.path.isdir(fileroot)):
            os.mkdir(fileroot)
        args['file'].save(filepath)
        return args['name'],filepath
    
    def post(self):
        name,img_path=self.save(self)
        img=cv2.imread(img_path)
        faces=face_cascade.get_face(img)
        if(len(faces)!=2):
            return {'error':'偵測不到人臉 請重新上傳'}
        else:
            return {'message':name+'已新增訓練樣本'}
        
class Train(Resource):
    def get(self):
        train.go_train()
        return {'message':'training is done'}
    
class Clock(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('name',required=True,help="Please write down your name")
        self.reqparse.add_argument('time',required=True,help="Please write down save time")
        self.reqparse.add_argument('log',required=True,help="Please write down your login or logout")
        self.reqparse.add_argument('status',required=True,help="Please write down your status")
    def post(self):
        args =self.reqparse.parse_args()
        save_time=args['time']
        save_name=args['name']
        save_log=args['log']
        status=args['status']
        if(status == 'error_'):
            save_log=status
        utc_time=datetime.datetime.utcfromtimestamp(float(save_time))
        tzutc_8 = datetime.timezone(datetime.timedelta(hours=8))
        local_dt = utc_time.astimezone(tzutc_8)
        img_file = local_dt.strftime('%Y_%m_%d_%H_%M_%S_%f')+'.jpg'
        img=cv2.imread(os.path.join('./tmp/upload',img_file))
        cv2.imwrite(os.path.abspath(os.path.join('./nas/Face',save_name,save_log,img_file)),img)
                    
        # 建立資料庫連線
        client=InfluxDBClient(host='192.168.0.6',port=8086,username='root',password='xMd2k5aK',database='rd')
        json_body = [
            {
                "measurement": save_log,
                "time": utc_time,
                "fields": {
                    "name": save_name,
                    'snapshot':save_log+'/'+img_file+'.jpg'
                }
            }
        ]
        client.write_points(json_body)
        client.close()
        return {'message':save_name+'打卡成功'}
        

class Insert_employee(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('name',required=True,help="Please write down your name")
        self.reqparse.add_argument('engname',required=True,help="Please write down save time")
        self.reqparse.add_argument('phone',required=True,help="Please write down your login or logout")
        self.reqparse.add_argument('years',required=True,help="Please write down your status")
        
    def post(self):
        args=self.reqparse.parse_args()
        name=args['name']
        engname=args['engname']
        phone=args['phone']
        years=args['years']
        db=pymysql.connect('192.168.0.5','root','xMd2k5aK','rd')
        cursor = db.cursor()
        # 資料庫查詢此類別最後一組id避免重複
        sql="SELECT id FROM employee WHERE id LIKE 'RD{0}%'".format(years)
        a=cursor.execute(sql)
        if(a==0):
            full_num='RD'+years+'00'
        else:
            result=cursor.fetchall()
            num=int(max(result)[0].split(years)[1])+1
        full_num='RD'+years+str(num)
        sql="""INSERT INTO `employee` (`id`, `name`, `english_name`, `phone`) VALUES ('{0}', '{1}', '{2}', '{3}')""".format(full_num,name,engname,phone)
        try:
        # 执行SQL语句
            cursor.execute(sql)
        # 提交到数据库执行
            db.commit()
        except:
        # 发生错误时回滚
            db.rollback()
 
        db.close()
        
        return {'message':str(args)}