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 HolidayModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'holiday'
        if(ID != None):
            self.data['no'] = ID if isinstance(ID, str) else str(ID) 
        self.data['year'] = None
        self.data['month'] = None
        self.data['day'] = None
        self.data['name'] = None
        self.data['is_work'] = None
    # ===== no ========================================
    def GetNo(self):
        return self.data['no'] if 'no' in self.data else None
    # ===== year ========================================
    def SetYear(self, year):
        return self.SetValue('year', year, str, False)
    def GetYear(self):
        return self.data['year'] if 'year' in self.data else None
    def GetOldYear(self):
        return self.change['id']
    def HasChangeYear(self):
        return 'year' in self.change
    # ===== month ========================================
    def SetMonth(self, month):
        return self.SetValue('month', month, str, False)
    def GetMonth(self):
        return self.data['month'] if 'month' in self.data else None
    def GetOldMonth(self):
        return self.change['month']
    def HasChangeMonth(self):
        return 'month' in self.change
    # ===== day ========================================
    def SetDay(self, day):
        return self.SetValue('day', day, str, False)
    def GetDay(self):
        return self.data['day'] if 'day' in self.data else None
    def GetOldDay(self):
        return self.change['day']
    def HasChangeDay(self):
        return 'day' in self.change
    # ===== name ========================================
    def SetName(self, name):
        return self.SetValue('name', name, str, False)
    def GetName(self):
        return self.data['name'] if 'name' in self.data else None
    def GetOldName(self):
        return self.change['name']
    def HasChangeName(self):
        return 'name' in self.change
    # ===== is_work ========================================
    def SetIsWork(self, is_work):
        return self.SetValue('is_work', is_work, bool, False)
    def GetIsWork(self):
        return self.data['is_work'] if 'is_work' in self.data else None
    def GetOldIsWork(self):
        return self.change['is_work']
    def HasChangeIsWork(self):
        return 'is_work' 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(),
            'year': self.GetYear(),
            'month': self.GetMonth(),
            'day': self.GetDay(),
            'name': self.GetName(),
            'is_work': self.GetIsWork(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = HolidayModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('holiday').Where('no', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetYear(script[1])
            model.SetMonth(script[2])
            model.SetDay(script[3])
            model.SetName(script[4])
            model.SetIsWork(script[5])
            model.SetCreated(script[6])
            model.SetUpdated(script[7])
            model.SetDeleted(script[8])
            model.isExist = True
        return model
    @staticmethod
    def FromDBByYearMonthDay(Year, Month, Day, log):            
        model = HolidayModel()
        mysql.SetLog(log)
        script = mysql.Select('holiday').Where('year', '=', Year).And('month', '=', Month).And('day', '=', Day).FetchOne()
        if isinstance(script, tuple):
            model.SetYear(script[1])
            model.SetMonth(script[2])
            model.SetDay(script[3])
            model.SetName(script[4])
            model.SetIsWork(script[5])
            model.SetCreated(script[6])
            model.SetUpdated(script[7])
            model.SetDeleted(script[8])
            model.isExist = True
        return model 
    @staticmethod
    def AllFromDB(log):
        models = []
        mysql.SetLog(log)
        script = mysql.Select('holiday').FetchAll()
        for row in script:
            model = HolidayModel(row[0])
            model.SetYear(row[1])
            model.SetMonth(row[2])
            model.SetDay(row[3])
            model.SetName(row[4])
            model.SetIsWork(row[5])
            model.SetCreated(row[6])
            model.SetUpdated(row[7])
            model.SetDeleted(row[8])
            model.isExist = True
            models.append(model)
        return models