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 FeaturesModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'features'
        if(ID != None):
            self.data['no'] = ID if isinstance(ID, str) else str(ID) 
        self.data['name'] = None
    # ===== no ========================================
    def GetNo(self):
        return self.data['no'] if 'no' in self.data else None
    # ===== major_title ========================================
    def SetMajorTitle(self, major_title):
        return self.SetValue('major_title', major_title, str, False)
    def GetMajorTitle(self):
        return self.data['major_title'] if 'major_title' in self.data else None
    def GetOldMajorTitle(self):
        return self.change['major_title']
    def HasChangeMajorTitle(self):
        return 'major_title' 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

    # ===== 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(),
            'major_title': self.GetMajorTitle(),
            'name': self.GetName(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = FeaturesModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('features').Where('no', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetMajorTitle(script[1])
            model.SetName(script[2])
            model.SetCreated(script[3])
            model.SetUpdated(script[4])
            model.SetDeleted(script[5])
            model.isExist = True
        return model
    @staticmethod
    def FromDBByName(Name, log):            
        model = FeaturesModel()
        mysql.SetLog(log)
        script = mysql.Select('features').Where('name', '=', Name).FetchOne()
        if isinstance(script, tuple):
            model.SetMajorTitle(script[1])
            model.SetName(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').FetchAll()
        for row in script:
            model = FeaturesModel(row[0])
            model.SetMajorTitle(row[1])
            model.SetName(row[2])
            model.SetCreated(row[3])
            model.SetUpdated(row[4])
            model.SetDeleted(row[5])
            model.isExist = True
            models.append(model)
        return models