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 UserFeatureModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'user_feature'
        self.data['id'] = ID if isinstance(ID, str) else str(ID)
        self.data['features'] = None
        self.data['description'] = None
    # ===== id ========================================
    def GetID(self):
        return self.data['id'] if 'id' in self.data else None
    def SetID(self, id):
        return self.SetValue('id', id, str, False)
    def GetOldID(self):
        return self.change['id']
    def HasChangeID(self):
        return 'id' in self.change
    # ===== features ========================================
    def SetFeatures(self, features):
        return self.SetValue('features', features, str, False)
    def GetFeatures(self):
        return self.data['features'] if 'features' in self.data else None
    def GetOldFeatures(self):
        return self.change['features']
    def HasChangeFeatures(self):
        return 'features' in self.change
    # ===== description ========================================
    def SetDescription(self, description):
        return self.SetValue('description', description, str, False)
    def GetDescription(self):
        return self.data['description'] if 'description' in self.data else None
    def GetOldDescription(self):
        return self.change['description']
    def HasChangeDescription(self):
        return 'description' 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('id', '=', self.data['id'])
        return script.FetchOne()
    def DeleteFromDB(self, log):
        script = mysql.Delete(self.table).Where('id', '=', self.data['id'])
        mysql.SetLog(log)
        return script.FetchOne()
    def ToDict(self):
        return {
            'ID': self.GetID(),
            'features': self.GetFeatures(),
            'description': self.GetDescription(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = UserFeatureModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('user_feature').Where('id', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetFeatures(script[1])
            model.SetDescription(script[2])
            model.SetCreated(script[3])
            model.SetUpdated(script[4])
            model.SetDeleted(script[5])
            model.isExist = True
        return model
    @staticmethod
    def AllFromDB(log):
        models = []
        mysql.SetLog(log)
        script = mysql.Select('user_feature').FetchAll()
        for row in script:
            model = UserFeatureModel(row[0])
            model.SetFeatures(row[1])
            model.SetDescription(row[2])
            model.SetCreated(row[3])
            model.SetUpdated(row[4])
            model.SetDeleted(row[5])
            model.isExist = True
            models.append(model)
        return models