from mysql_model import BaseModel
import os, json, base64, requests
from dbsql import MySQL


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)

# ========== 功能角色關係資料庫模型 ==========
class FeaturesRoleRelationModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'features_role_relation'
        if(ID != None):
            self.data['no'] = ID if isinstance(ID, str) else str(ID) 
        self.data['role_id'] = None
        self.data['features_id'] = None
    # ===== no ========================================
    def GetNo(self):
        return self.data['no'] if 'no' in self.data else None
    # ===== role_id ========================================
    def SetRoleId(self, role_id):
        return self.SetValue('role_id', role_id, int, False)
    def GetRoleId(self):
        return self.data['role_id'] if 'role_id' in self.data else None
    def GetOldRoleId(self):
        return self.change['role_id']
    def HasChangeRoleId(self):
        return 'role_id' in self.change
    # ===== features_id ========================================
    def SetFeaturesId(self, features_id):
        return self.SetValue('features_id', features_id, int, False)
    def GetFeaturesId(self):
        return self.data['features_id'] if 'features_id' in self.data else None
    def GetOldFeaturesId(self):
        return self.change['features_id']
    def HasChangeFeaturesId(self):
        return 'features_id' 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(),
            'role_id': self.GetRoleId(),
            'features_id': self.GetFeaturesId(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = FeaturesRoleRelationModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('features_role_relation').Where('no', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetRoleId(script[1])
            model.SetFeaturesId(script[2])
            model.SetCreated(script[3])
            model.SetUpdated(script[4])
            model.SetDeleted(script[5])
            model.isExist = True
        return model
    @staticmethod
    def FromDBByRoleFeatures(Role, Features, log):            
        model = FeaturesRoleRelationModel()
        mysql.SetLog(log)
        script = mysql.Select('features_role_relation').Where('role_id', '=', Role).And('features_id', '=', Features).FetchOne()
        if isinstance(script, tuple):
            model.SetRoleId(script[1])
            model.SetFeaturesId(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('features_role_relation').FetchAll()
        for row in script:
            model = FeaturesRoleRelationModel(row[0])
            model.SetRoleId(row[1])
            model.SetFeaturesId(row[2])
            model.SetCreated(row[3])
            model.SetUpdated(row[4])
            model.SetDeleted(row[5])
            model.isExist = True
            models.append(model)
        return models