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 DepartLeaveUnitModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'depart_leave_unit'
        if(ID != None):
            self.data['no'] = ID if isinstance(ID, str) else str(ID) 
        self.data['department'] = None
        self.data['signing_unit_1'] = None
        self.data['signing_unit_2'] = None
        self.data['signing_unit_3'] = None
    # ===== no ========================================
    def GetNo(self):
        return self.data['no'] if 'no' in self.data else None
    # ===== department ========================================
    def SetDepartment(self, department):
        return self.SetValue('department', department, str, False)
    def GetDepartment(self):
        return self.data['department'] if 'department' in self.data else None
    def GetOldDepartment(self):
        return self.change['department']
    def HasChangeDepartment(self):
        return 'department' in self.change
    # ===== signing_unit_1 ========================================
    def SetSigningUnit1(self, signing_unit_1):
        return self.SetValue('signing_unit_1', signing_unit_1, str, False)
    def GetSigningUnit1(self):
        return self.data['signing_unit_1'] if 'signing_unit_1' in self.data else None
    def GetOldSigningUnit1(self):
        return self.change['signing_unit_1']
    def HasChangeSigningUnit1(self):
        return 'signing_unit_1' in self.change
    # ===== signing_unit_2 ========================================
    def SetSigningUnit2(self, signing_unit_2):
        return self.SetValue('signing_unit_2', signing_unit_2, str, False)
    def GetSigningUnit2(self):
        return self.data['signing_unit_2'] if 'signing_unit_2' in self.data else None
    def GetOldSigningUnit2(self):
        return self.change['signing_unit_2']
    def HasChangeSigningUnit2(self):
        return 'signing_unit_2' in self.change
    # ===== signing_unit_3 ========================================
    def SetSigningUnit3(self, signing_unit_3):
        return self.SetValue('signing_unit_3', signing_unit_3, str, False)
    def GetSigningUnit3(self):
        return self.data['signing_unit_3'] if 'signing_unit_3' in self.data else None
    def GetOldSigningUnit3(self):
        return self.change['signing_unit_3']
    def HasChangeSigningUnit3(self):
        return 'signing_unit_3' 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(),
            'department': self.GetDepartment(),
            'signing_unit_1': self.GetSigningUnit1(),
            'signing_unit_2': self.GetSigningUnit2(),
            'signing_unit_3': self.GetSigningUnit3(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = DepartLeaveUnitModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('depart_leave_unit').Where('no', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetDepartment(script[1])
            model.SetSigningUnit1(script[2])
            model.SetSigningUnit2(script[3])
            model.SetSigningUnit3(script[4])
            model.SetCreated(script[5])
            model.SetUpdated(script[6])
            model.SetDeleted(script[7])
            model.isExist = True
        return model
    @staticmethod
    def FromDBByDepartment(Department, log):            
        model = DepartLeaveUnitModel()
        mysql.SetLog(log)
        script = mysql.Select('depart_leave_unit').Where('department', '=', Department).FetchOne()
        if isinstance(script, tuple):
            model.SetDepartment(script[1])
            model.SetSigningUnit1(script[2])
            model.SetSigningUnit2(script[3])
            model.SetSigningUnit3(script[4])
            model.SetCreated(script[5])
            model.SetUpdated(script[6])
            model.SetDeleted(script[7])
            model.isExist = True
        return model    
    @staticmethod
    def AllFromDB(log):
        models = []
        mysql.SetLog(log)
        script = mysql.Select('depart_leave_unit').FetchAll()
        for row in script:
            model = DepartLeaveUnitModel(row[0])
            model.SetDepartment(row[1])
            model.SetSigningUnit1(row[2])
            model.SetSigningUnit2(row[3])
            model.SetSigningUnit3(row[4])
            model.SetCreated(row[5])
            model.SetUpdated(row[6])
            model.SetDeleted(row[7])
            model.isExist = True
            models.append(model)
        return models