from passlib.hash import pbkdf2_sha256 as sha256
from datetime import datetime
from io import BytesIO
from PIL import Image
from dbsql import MySQL
# from mtcnn import MTCNN
from matplotlib import pyplot as plt
import os, json, base64, requests
from CM26EWH_model import insert_face,delete_person

env = os.environ
host = env['MYSQL_HOST']      if 'MYSQL_HOST' in env else "192.168.6.194"
port = int(env['MYSQL_PORT']) if 'MYSQL_PORT' in env else 23306
usr  = env['MYSQL_USR']       if 'MYSQL_USR'  in env else "root"
pwd  = env['MYSQL_PWD']       if 'MYSQL_PWD'  in env else "123456"
db   = env['MYSQL_DB']        if 'MYSQL_DB'   in env else "ecom"
mysql = MySQL(host, port, usr, pwd, db)
# detector = MTCNN()

# ===== 基礎資料庫模型 =====
class BaseModel(object):
    def __init__(self):
        self.data = { 'created': self.GetNow(), 'updated': self.GetNow(), }
        self.change = {}
        self.isExist = False
    def IsEnabled(self):
        return self.GetDeleted() is None
    def SetCreated(self, created=None):
        self.data['created'] = self.GetNow() if created is None else created
    def SetUpdated(self, updated=None):
        self.data['updated'] = self.GetNow() if updated is None else updated
    def SetDeleted(self, deleted=None):
        self.data['deleted'] = deleted
    def SetValue(self, key, value, valueType, canNull):
        if value is not None or canNull:
            value1 = value if isinstance(value, valueType) or canNull else valueType(value)
            if key in self.data and self.data[key] is not None:
                value2 = self.data[key] if isinstance(self.data[key], valueType) else valueType(self.data[key])
                if value1 != value2:
                    self.change[key] = self.data[key]
            self.data[key] = value1
            self.SetUpdated()
            return True
        return False
    def GetCreated(self):
        return self.StringToDatetime(self.data['created']) if 'created' in self.data and self.data['created'] is not None else None
    def GetUpdated(self):
        return self.StringToDatetime(self.data['updated']) if 'updated' in self.data and self.data['updated'] is not None else None
    def GetDeleted(self):
        return self.StringToDatetime(self.data['deleted']) if 'deleted' in self.data and self.data['deleted'] is not None else None
    def GetHash(self, password):
        return "" if password is None or len(password) == 0 else sha256.hash(password)
    def GetNow(self):
        return self.DatetimeToString(datetime.now())
    def DatetimeToString(self, _datetime):
        if isinstance(_datetime, datetime):
            return "{0}{1}".format(_datetime.year - 1911, _datetime.strftime('%m%d%H%M%S'))
        else:
            return None
    def StringToDatetime(self, _string):
        if isinstance(_string, str):
            y = int(_string[0:3]) + 1911
            _datetime = datetime.strptime(_string[3:13], "%m%d%H%M%S")
            _datetime = _datetime.replace(y)
            return _datetime
        else:
            return None
        
# ========== 簽呈狀況資料庫模型 ==========
class LeaveSigningStatusModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'leave_signing_status'
        if(ID != None):
            self.data['no'] = ID if isinstance(ID, str) else str(ID) 
        self.data['leave_off_work_no'] = None
        self.data['depart_leave_unit_department'] = None
        self.data['signing_status_1'] = None
        self.data['signing_status_2'] = None
        self.data['signing_status_3'] = None
        self.data['signing_status_4'] = None
    # ===== no ========================================
    def GetNo(self):
        return self.data['no'] if 'no' in self.data else None
    # ===== leave_off_work_no ========================================
    def SetLeaveOffWorkNo(self, leave_off_work_no):
        return self.SetValue('leave_off_work_no', leave_off_work_no, str, False)
    def GetLeaveOffWorkNo(self):
        return self.data['leave_off_work_no'] if 'leave_off_work_no' in self.data else None
    def GetOldLeaveOffWorkNo(self):
        return self.change['leave_off_work_no']
    def HasChangeLeaveOffWorkNo(self):
        return 'leave_off_work_no' in self.change
    # ===== depart_leave_unit_department ========================================
    def SetDepartLeaveUnitDepartment(self, depart_leave_unit_department):
        return self.SetValue('depart_leave_unit_department', depart_leave_unit_department, str, False)
    def GetDepartLeaveUnitDepartment(self):
        return self.data['depart_leave_unit_department'] if 'depart_leave_unit_department' in self.data else None
    def GetOldDepartLeaveUnitDepartment(self):
        return self.change['depart_leave_unit_department']
    def HasChangeDepartLeaveUnitDepartment(self):
        return 'depart_leave_unit_department' in self.change
    # ===== signing_status_1 ========================================
    def SetSigningStatus1(self, signing_status_1):
        return self.SetValue('signing_status_1', signing_status_1, str, False)
    def GetSigningStatus1(self):
        return self.data['signing_status_1'] if 'signing_status_1' in self.data else None
    def GetOldSigningStatus1(self):
        return self.change['signing_status_1']
    def HasChangeSigningStatus1(self):
        return 'signing_status_1' in self.change
    # ===== signing_status_2 ========================================
    def SetSigningStatus2(self, signing_status_2):
        return self.SetValue('signing_status_2', signing_status_2, str, False)
    def GetSigningStatus2(self):
        return self.data['signing_status_2'] if 'signing_status_2' in self.data else None
    def GetOldSigningStatus2(self):
        return self.change['signing_status_2']
    def HasChangeSigningStatus2(self):
        return 'signing_status_2' in self.change
    # ===== signing_status_3 ========================================
    def SetSigningStatus3(self, signing_status_3):
        return self.SetValue('signing_status_3', signing_status_3, str, False)
    def GetSigningStatus3(self):
        return self.data['signing_status_3'] if 'signing_status_3' in self.data else None
    def GetOldSigningStatus3(self):
        return self.change['signing_status_3']
    def HasChangeSigningStatus3(self):
        return 'signing_status_3' in self.change
    # ===== signing_status_4 ========================================
    def SetSigningStatus4(self, signing_status_4):
        return self.SetValue('signing_status_4', signing_status_4, str, False)
    def GetSigningStatus4(self):
        return self.data['signing_status_4'] if 'signing_status_4' in self.data else None
    def GetOldSigningStatus4(self):
        return self.change['signing_status_4']
    def HasChangeSigningStatus4(self):
        return 'signing_status_4' in self.change

    # ===== operate database ========================================
    def InsertToDB(self, log):
        keys = self.data.keys()
        values = [ self.data[x] for x in keys ]
        mysql.SetLog(log)
        script = mysql.Insert(self.table, keys, values)
        return script.Fetch()
    def UpdateToDB(self, log):
        script = None
        for k in self.data.keys():
            mysql.SetLog(log)
            script = mysql.Update(self.table, k, self.data[k]) if script is None else script.Add(k, self.data[k])
        script = script.Where('no', '=', self.data['no'])
        return script.FetchOne()
    def DeleteFromDB(self, log):
        script = mysql.Delete(self.table).Where('no', '=', self.data['no'])
        mysql.SetLog(log)
        return script.FetchOne()
    def ToDict(self):
        return {
            'no': self.GetNo(),
            'leave_off_work_no': self.GetLeaveOffWorkNo(),
            'depart_leave_unit_department': self.GetDepartLeaveUnitDepartment(),
            'signing_status_1': self.GetSigningStatus1(),
            'signing_status_2': self.GetSigningStatus2(),
            'signing_status_3': self.GetSigningStatus3(),
            'signing_status_4': self.GetSigningStatus4(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = LeaveSigningStatusModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('leave_signing_status').Where('no', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetLeaveOffWorkNo(script[1])
            model.SetDepartLeaveUnitDepartment(script[2])
            model.SetSigningStatus1(script[3])
            model.SetSigningStatus2(script[4])
            model.SetSigningStatus3(script[5])
            model.SetSigningStatus4(script[6])
            model.SetCreated(script[7])
            model.SetUpdated(script[8])
            model.SetDeleted(script[9])
            model.isExist = True
        return model
    @staticmethod
    def FromDBByLeaveOffWorkNo(LeaveOffWorkNo, log):            
        model = LeaveSigningStatusModel()
        mysql.SetLog(log)
        script = mysql.Select('leave_signing_status').Where('leave_off_work_no', '=', LeaveOffWorkNo).FetchOne()
        if isinstance(script, tuple):
            model.SetLeaveOffWorkNo(script[1])
            model.SetDepartLeaveUnitDepartment(script[2])
            model.SetSigningStatus1(script[3])
            model.SetSigningStatus2(script[4])
            model.SetSigningStatus3(script[5])
            model.SetSigningStatus4(script[6])
            model.SetCreated(script[7])
            model.SetUpdated(script[8])
            model.SetDeleted(script[9])
            model.isExist = True
        return model    
    @staticmethod
    def AllFromDB(log):
        models = []
        mysql.SetLog(log)
        script = mysql.Select('leave_signing_status').FetchAll()
        for row in script:
            model = LeaveSigningStatusModel(row[0])
            model.SetLeaveOffWorkNo(row[1])
            model.SetDepartLeaveUnitDepartment(row[2])
            model.SetSigningStatus1(row[3])
            model.SetSigningStatus2(row[4])
            model.SetSigningStatus3(row[5])
            model.SetSigningStatus4(row[6])
            model.SetCreated(row[7])
            model.SetUpdated(row[8])
            model.SetDeleted(row[9])
            model.isExist = True
            models.append(model)
        return models