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 OvertimeModel(BaseModel):
    def __init__(self, ID=None):
        super().__init__()
        self.table = 'overtime'
        if(ID != None):
            self.data['no'] = ID if isinstance(ID, str) else str(ID) 
        self.data['person_id'] = None
        self.data['department_id'] = None
        self.data['date'] = None
        self.data['start'] = None
        self.data['end'] = None
        self.data['hour'] = None
        self.data['day_category'] = None
        self.data['reason'] = None
        self.data['is_key'] = None
        self.data['status'] = None
    # ===== no ========================================
    def GetNo(self):
        return self.data['no'] if 'no' in self.data else None
    # ===== person_id ========================================
    def SetPersonId(self, person_id):
        return self.SetValue('person_id', person_id, str, False)
    def GetPersonId(self):
        return self.data['person_id'] if 'person_id' in self.data else None
    def GetOldPersonId(self):
        return self.change['person_id']
    def HasChangePersonId(self):
        return 'person_id' in self.change
    # ===== department_id ========================================
    def SetDepartmentId(self, department_id):
        return self.SetValue('department_id', department_id, str, False)
    def GetDepartmentId(self):
        return self.data['department_id'] if 'department_id' in self.data else None
    def GetOldDepartmentId(self):
        return self.change['department_id']
    def HasChangeDepartmentId(self):
        return 'department_id' in self.change
    # ===== date ========================================
    def SetDate(self, date):
        return self.SetValue('date', date, str, False)
    def GetDate(self):
        return self.data['date'] if 'date' in self.data else None
    def GetOldDate(self):
        return self.change['date']
    def HasChangeDate(self):
        return 'date' in self.change
    # ===== start ========================================
    def SetStart(self, start):
        return self.SetValue('start', start, str, False)
    def GetStart(self):
        return self.data['start'] if 'start' in self.data else None
    def GetOldStart(self):
        return self.change['start']
    def HasChangeStart(self):
        return 'start' in self.change
    # ===== end ========================================
    def SetEnd(self, end):
        return self.SetValue('end', end, str, False)
    def GetEnd(self):
        return self.data['end'] if 'end' in self.data else None
    def GetOldEnd(self):
        return self.change['end']
    def HasChangeEnd(self):
        return 'end' in self.change
    # ===== hour ========================================
    def SetHour(self, hour):
        return self.SetValue('hour', hour, float, False)
    def GetHour(self):
        return self.data['hour'] if 'hour' in self.data else None
    def GetOldHour(self):
        return self.change['hour']
    def HasChangeHour(self):
        return 'hour' in self.change
    # ===== day_category ========================================
    def SetDayCategory(self, day_category):
        return self.SetValue('day_category', day_category, str, False)
    def GetDayCategory(self):
        return self.data['day_category'] if 'day_category' in self.data else None
    def GetOldDayCategory(self):
        return self.change['day_category']
    def HasChangeDayCategory(self):
        return 'day_category' in self.change
    # ===== reason ========================================
    def SetReason(self, reason):
        return self.SetValue('reason', reason, str, False)
    def GetReason(self):
        return self.data['reason'] if 'reason' in self.data else None
    def GetOldReason(self):
        return self.change['reason']
    def HasChangeReason(self):
        return 'reason' in self.change
    # ===== is_key ========================================
    def SetIsKey(self, is_key):
        return self.SetValue('is_key', is_key, bool, False)
    def GetIsKey(self):
        return self.data['is_key'] if 'is_key' in self.data else None
    def GetOldIsKey(self):
        return self.change['is_key']
    def HasChangeIsKey(self):
        return 'is_key' in self.change
    # ===== status ========================================
    def SetStatus(self, status):
        return self.SetValue('status', status, str, False)
    def GetStatus(self):
        return self.data['status'] if 'status' in self.data else None
    def GetOldStatus(self):
        return self.change['status']
    def HasChangeStatus(self):
        return 'status' 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(),
            'person_id': self.GetPersonId(),
            'department_id': self.GetDepartmentId(),
            'date': self.GetDate(),
            'start': self.GetStart(),
            'end': self.GetEnd(),
            'hour': self.GetHour(),
            'day_category': self.GetDayCategory(),
            'reason': self.GetReason(),
            'is_key': self.GetIsKey(),
            'status': self.GetStatus(),
        }
    # ===== other ========================================
    @staticmethod
    def FromDB(ID, log):            
        model = OvertimeModel(ID)
        mysql.SetLog(log)
        script = mysql.Select('overtime').Where('no', '=', ID).FetchOne()
        if isinstance(script, tuple):
            model.SetPersonId(script[1])
            model.SetDepartmentId(script[2])
            model.SetDate(script[3])
            model.SetStart(script[4])
            model.SetEnd(script[5])
            model.SetHour(script[6])
            model.SetDayCategory(script[7])
            model.SetReason(script[8])
            model.SetIsKey(script[9])
            model.SetStatus(script[10])
            model.SetCreated(script[11])
            model.SetUpdated(script[12])
            model.SetDeleted(script[13])
            model.isExist = True
        return model
    @staticmethod
    def FromDBByDate(Person, Date, log):            
        model = OvertimeModel()
        mysql.SetLog(log)
        script = mysql.Select('overtime').Where('person_id', '=', Person).And('date', '=', Date).FetchOne()
        if isinstance(script, tuple):
            model.SetPersonId(script[1])
            model.SetDepartmentId(script[2])
            model.SetDate(script[3])
            model.SetStart(script[4])
            model.SetEnd(script[5])
            model.SetHour(script[6])
            model.SetDayCategory(script[7])
            model.SetReason(script[8])
            model.SetIsKey(script[9])
            model.SetStatus(script[10])
            model.SetCreated(script[11])
            model.SetUpdated(script[12])
            model.SetDeleted(script[13])
            model.isExist = True
        return model    
    @staticmethod
    def AllFromDB(log):
        models = []
        mysql.SetLog(log)
        script = mysql.Select('overtime').FetchAll()
        for row in script:
            model = OvertimeModel(row[0])
            model.SetPersonId(row[1])
            model.SetDepartmentId(row[2])
            model.SetDate(row[3])
            model.SetStart(row[4])
            model.SetEnd(row[5])
            model.SetHour(row[6])
            model.SetDayCategory(row[7])
            model.SetReason(row[8])
            model.SetIsKey(row[9])
            model.SetStatus(row[10])
            model.SetCreated(row[11])
            model.SetUpdated(row[12])
            model.SetDeleted(row[13])
            model.isExist = True
            models.append(model)
        return models