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 DeviceShiftRelationModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'device_shift_relation'
        if(ID != None):
            self.data['no'] = ID if isinstance(ID, str) else str(ID) 
        self.data['device_id'] = None
        self.data['shift_no'] = None
        self.data['note'] = None
    # ===== no ========================================
    def GetNo(self):
        return self.data['no'] if 'no' in self.data else None
    # ===== device_id ========================================
    def SetDeviceId(self, device_id):
        return self.SetValue('device_id', device_id, str, False)
    def GetDeviceId(self):
        return self.data['device_id'] if 'device_id' in self.data else None
    def GetOldDeviceId(self):
        return self.change['device_id']
    def HasChangeDeviceId(self):
        return 'device_id' in self.change
    # ===== shift_no ========================================
    def SetShiftNo(self, shift_no):
        return self.SetValue('shift_no', shift_no, str, False)
    def GetShiftNo(self):
        return self.data['shift_no'] if 'shift_no' in self.data else None
    def GetOldShiftNo(self):
        return self.change['shift_no']
    def HasChangeShiftNo(self):
        return 'shift_no' in self.change
    # ===== note ========================================
    def SetNote(self, note):
        return self.SetValue('note', note, str, True)
    def GetNote(self):
        return self.data['note'] if 'note' in self.data else None
    def GetOldNote(self):
        return self.change['note']
    def HasChangeNote(self):
        return 'note' 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(),
            'device_id': self.GetDeviceId(),
            'shift_no': self.GetShiftNo(),
            'note': self.GetNote(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = DeviceShiftRelationModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('device_shift_relation').Where('no', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetDeviceId(script[1])
            model.SetShiftNo(script[2])
            model.SetNote(script[3])
            model.SetCreated(script[4])
            model.SetUpdated(script[5])
            model.SetDeleted(script[6])
            model.isExist = True
        return model  
    @staticmethod
    def FromDBByDeviceIdShiftNo(DeviceId, ShiftNo, log):            
        model = DeviceShiftRelationModel()
        mysql.SetLog(log)
        script = mysql.Select('device_shift_relation').Where('device_id', '=', DeviceId).And('shift_no', '=', ShiftNo).FetchOne()
        if isinstance(script, tuple):
            model.SetDeviceId(script[1])
            model.SetShiftNo(script[2])
            model.SetNote(script[3])
            model.SetCreated(script[4])
            model.SetUpdated(script[5])
            model.SetDeleted(script[6])
            model.isExist = True
        return model    
    @staticmethod
    def AllFromDB(log):
        models = []
        mysql.SetLog(log)
        script = mysql.Select('device_shift_relation').FetchAll()
        for row in script:
            model = DeviceShiftRelationModel(row[0])
            model.SetDeviceId(row[1])
            model.SetShiftNo(row[2])
            model.SetNote(row[3])
            model.SetCreated(row[4])
            model.SetUpdated(row[5])
            model.SetDeleted(row[6])
            model.isExist = True
            models.append(model)
        return models