from base_resource import BaseResource
from holiday_model import HolidayModel
from werkzeug.datastructures import FileStorage
import os, werkzeug, base64, pandas as pd
from datetime import datetime

# ========== 新增請假紀錄 ==========
class HolidayInsert(BaseResource):
    def __init__(self):
        super().__init__("InsertHoliday")
        self.parser.add_argument('year', help="年")
        self.parser.add_argument('month', help="月")
        self.parser.add_argument('day', help="日")
        self.parser.add_argument('name', help="例假日名稱")
        self.parser.add_argument('is_work', help="是否上班")       #傳任何字都是True，空字串或數字0是False 
    def post(self):
        args = self.parser.parse_args()
        model = HolidayModel.FromDBByYearMonthDay(args['year'],args['month'],args['day'], self.log.SetMessage)
        if not model.isExist:
            model.SetYear(args['year'])
            model.SetMonth(args['month'])
            model.SetDay(args['day'])
            model.SetName(args['name'])
            model.SetIsWork(args['is_work'])
            if model.InsertToDB(self.log.SetMessage):
                self.message = "year：{0} month：{1} day：{2} inserted".format(args['year'],args['month'],args['day'])
            else:
                self.message = "year：{0} month：{1} day：{2} insert failed".format(args['year'],args['month'],args['day'])
        else:
            self.message = "year：{0} month：{1} day：{2} is exist in database".format(args['year'],args['month'],args['day'])
        return self.GetResponse()

# ========== 新增請假紀錄-excel ==========
class HolidayInsertWithExcel(BaseResource):
    def __init__(self):
        super().__init__("HolidayInsertWithExcel")
        self.parser.add_argument('excel', required=True, type=FileStorage, location='files')
    def post(self):
        args = self.parser.parse_args()
        now = datetime.now()
        now = datetime.timestamp(now)
        filename = "{0}.xlsx".format(os.path.join("static", "excel", str(now)))
        args['excel'].save(filename)
        excel = pd.read_excel(filename,header=None)
        insert = []
        not_insert = []
        if (excel.iloc[0,0]=="假期名稱" and excel.iloc[0,1]=="日期(yyy/mm/dd)" and excel.iloc[0,2]=="是否上班(是/否)"):
            for x in excel.values:
                if(x[0]==excel.iloc[0,0]):
                    continue
                date=x[1].split('/')
                if (isinstance(x[0],str) and isinstance(x[1],str)):
                    model = HolidayModel.FromDBByYearMonthDay(date[0],date[1],date[2], self.log.SetMessage)
                    if not model.isExist:
                        if(x[2] == "是" or x[2] == "否"):
                            if(x[2] == "是"):
                                model.SetIsWork(1)
                            else:
                                model.SetIsWork(0)
                            model.SetYear(date[0])
                            model.SetMonth(date[1])
                            model.SetDay(date[2])
                            model.SetName(x[0])
                            if model.InsertToDB(self.log.SetMessage):
                                insert.append(x[0])
                            else:
                                not_insert.append(x[0])
                        else:
                            not_insert.append(x[0])
                    else:
                        not_insert.append(x[0])
            self.message = "Holiday {0} inserted, Holiday {1} insert failed, {2}".format(len(insert), len(not_insert), ', '.join(not_insert))
        else:
            self.message = "File format error"
        return self.GetResponse()
# ========== 更新請假紀錄 ==========
class HolidayUpdate(BaseResource):
    def __init__(self):
        super().__init__("UpdateHoliday")
        self.parser.add_argument('no', required=True, help="例假日編號")        
        self.parser.add_argument('year', help="年")
        self.parser.add_argument('month', help="月")
        self.parser.add_argument('day', help="日")
        self.parser.add_argument('name', help="例假日名稱")
        self.parser.add_argument('is_work', help="是否上班")    #傳任何字都是True，空字串或數字0是False 
    def post(self):
        args = self.parser.parse_args()
        model = HolidayModel.FromDB(args['no'], self.log.SetMessage)
        if model.isExist:
            model.SetYear(args['year'])
            model.SetMonth(args['month'])
            model.SetDay(args['day'])
            model.SetName(args['name'])
            model.SetIsWork(args['is_work'])
            if model.UpdateToDB(self.log.SetMessage):
                self.message = []
                if model.HasChangeYear():
                    self.message.append(
                        "Year: {0} -> {1}".format(model.GetOldYear(), model.GetYear())
                    )
                if model.HasChangeMonth():
                    self.message.append(
                        "Month: {0} -> {1}".format(model.GetOldMonth(), model.GetMonth())
                    )
                if model.HasChangeDay():
                    self.message.append(
                        "Day: {0} -> {1}".format(model.GetOldDay(), model.GetDay())
                    )
                if model.HasChangeName():
                    self.message.append(
                        "Name: {0} -> {1}".format(model.GetOldName(), model.GetName())
                    )    
                if model.HasChangeIsWork():
                    self.message.append(
                        "IsWork: {0} -> {1}".format(model.GetOldIsWork(), model.GetIsWork())
                    )                    
                self.message = ", ".join(self.message) if len(self.message) > 0 else ""
            else:
                self.message = "name：{0} update failed".format(args['name'])
        else:
            self.message = "name：{0} isn't exist in database".format(args['name'])
        return self.GetResponse()
# ========== 刪除請假紀錄 ==========
class HolidayDelete(BaseResource):
    def __init__(self):
        super().__init__("DeleteHoliday")
        self.parser.add_argument('no', required=True)
    def post(self):
        args = self.parser.parse_args()
        model = HolidayModel.FromDB(args['no'], self.log.SetMessage)
        if model.isExist:
            if model.DeleteFromDB(self.log.SetMessage):
                self.message = "{0} deleted".format(args['no'], model.GetNow())
            else:
                self.message = "{0} delete failed".format(args['no'])
        else:
            self.message = "{0} isn't exist in database".format(args['no'])
        return self.GetResponse()    
# ========== 查詢所有請假紀錄 ==========
class HolidaySelectAll(BaseResource):
    def __init__(self):
        super().__init__("SelectHoliday")
    def post(self, ID=None):
        models = HolidayModel.AllFromDB(self.log.SetMessage)
        if len(models) > 0:
            self.data = []
            for model in models:
                self.data.append(model.ToDict())
            self.message = "{0} selected".format(len(self.data))
        else:
            self.message = "no data in database"
        return self.GetResponse()    