from base_resource import BaseResource,SendBaseResource
from mysql_model import UserModel,UserAuthModel
from docx import Document
from io import BytesIO

# ========== 新增使用者資源 ==========
class UserInsert(BaseResource):
    def __init__(self):
        super().__init__("InsertUser")
        self.parser.add_argument('id', required=True, help="上限 10 字")
        self.parser.add_argument('person_id', required=True, help="上限 10 字")
        self.parser.add_argument('name', required=True, help="上限 10 字")
        self.parser.add_argument('department', required=True, help="上限 10 字")
        self.parser.add_argument('role')
        self.parser.add_argument('on_board', required=True, help="上限 15 字")
        self.parser.add_argument('username', required=True, help="上限 15 字")
        self.parser.add_argument('password', required=True)
        self.parser.add_argument('email', required=True, help="上限 25 字")
    def post(self):
        args = self.parser.parse_args()
        model = UserModel.FromDB(args['id'], self.log.SetMessage)
        if not model.isExist:
            model.SetPersonId(args['person_id'])
            model.SetName(args['name'])
            model.SetDepartment(args['department'])
            model.SetRole(args['role'])
            model.SetOnBoard(args['on_board'])
            model.SetUsername(args['username'])
            model.SetPassword(args['password'])
            model.SetEmail(args['email'])
            if model.InsertToDB():
                self.message = "{0} inserted".format(args['id'])
            else:
                self.message = "{0} insert failed".format(args['id'])
        else:
            self.message = "{0} is exist in database".format(args['id'])
        return self.GetResponse()
# ========== 更新使用者資源 ==========
class UserUpdate(BaseResource):
    def __init__(self):
        super().__init__("UpdateUser")
        self.parser.add_argument('id', required=True, help="上限 10 字")
        self.parser.add_argument('person_id', required=True, help="上限 10 字")
        self.parser.add_argument('name', help="上限 10 字")
        self.parser.add_argument('department', required=True, help="上限 10 字")
        self.parser.add_argument('role')
        self.parser.add_argument('on_board', required=True, help="上限 15 字")
#         self.parser.add_argument('username', help="上限 15 字")
#         self.parser.add_argument('password')
        self.parser.add_argument('email', required=True, help="上限 25 字")
    def post(self):
        args = self.parser.parse_args()
        model = UserModel.FromDB(args['id'], self.log.SetMessage)
        if model.isExist:
            model.SetPersonId(args['person_id'])
            model.SetName(args['name'])
            model.SetDepartment(args['department'])
            model.SetRole(args['role'])
            model.SetOnBoard(args['on_board'])
#             model.SetUsername(args['username'])
#             model.SetPassword(args['password'])
            model.SetEmail(args['email'])
            if model.UpdateToDB():
                self.message = []
                if model.HasChangePersonId():
                    self.message.append(
                        "PersonId: {0} -> {1}".format(model.GetOldPersonId(), model.GetPersonId())
                    )
                if model.HasChangeName():
                    self.message.append(
                        "Name: {0} -> {1}".format(model.GetOldName(), model.GetName())
                    )
                if model.HasChangeDepartment():
                    self.message.append(
                        "Department: {0} -> {1}".format(model.GetOldDepartment(), model.GetDepartment())
                    )
                if model.HasChangeRole():
                    self.message.append(
                        "Role: {0} -> {1}".format(model.GetOldRole(), model.GetRole())
                    )
                if model.HasChangeOnBoard():
                    self.message.append(
                        "OnBoard: {0} -> {1}".format(model.GetOldOnBoard(), model.GetOnBoard())
                    )
#                 if model.HasChangeUsername():
#                     self.message.append(
#                         "Username: {0} -> {1}".format(model.GetOldUsername(), model.GetUsername())
#                     )
#                 if model.HasChangePassword():
#                     self.message.append(
#                         "Password: {0} -> {1}".format(model.GetOldPassword(), model.GetPassword())
#                     )
                if model.HasChangeEmail():
                    self.message.append(
                        "Email: {0} -> {1}".format(model.GetOldEmail(), model.GetEmail())
                    )
                self.message = ", ".join(self.message) if len(self.message) > 0 else ""
            else:
                self.message = "{0} update failed".format(args['id'])
        else:
            self.message = "{0} isn't exist in database".format(args['id'])
        return self.GetResponse()
# ========== 更新使用者密碼資源 ==========
class UserUpdatePassword(BaseResource):
    def __init__(self):
        super().__init__("UpdateUser")
        self.parser.add_argument('id', required=True, help="上限 10 字")
        self.parser.add_argument('username', help="上限 15 字")
        self.parser.add_argument('password')
    def post(self):
        args = self.parser.parse_args()
        model = UserModel.FromDB(args['id'], self.log.SetMessage)
        if model.isExist:
            model.SetUsername(args['username'])
            model.SetPassword(args['password'])
            if model.UpdateToDBForPassword():
                self.message = []
                if model.HasChangeUsername():
                    self.message.append(
                        "Username: {0} -> {1}".format(model.GetOldUsername(), model.GetUsername())
                    )
                if model.HasChangePassword():
                    self.message.append(
                        "Password: {0} -> {1}".format(model.GetOldPassword(), model.GetPassword())
                    )
                self.message = ", ".join(self.message) if len(self.message) > 0 else ""
            else:
                self.message = "{0} update failed".format(args['id'])
        else:
            self.message = "{0} isn't exist in database".format(args['id'])
        return self.GetResponse()
# ========== 刪除使用者資源 ==========
class UserDelete(BaseResource):
    def __init__(self):
        super().__init__("DeleteUser")
        self.parser.add_argument('id', required=True, help="上限 10 字")
    def post(self):
        args = self.parser.parse_args()
        model = UserModel.FromDB(args['id'], self.log.SetMessage)
        if model.isExist:
            if model.DeleteFromDB():
                self.message = "{0} deleted".format(args['id'])
            else:
                self.message = "{0} delete failed".format(args['id'])
        else:
            self.message = "{0} isn't exist in database".format(args['id'])
        return self.GetResponse()
# ========== 使用者驗證 ==========
class UserAuth(BaseResource):
    def __init__(self):
        super().__init__("UserAuthModel")
        self.parser.add_argument('username', required=True,)
        self.parser.add_argument('password', required=True)
    def post(self):
        args = self.parser.parse_args()
        model = UserAuthModel.FromDB(args['username'],args['password'], self.log.SetMessage)
        if not model.isExist:
            self.message = "{0} is not exist".format(args['username'])
        else:
            if(model.isauthed):
                self.message = "{0} auth success".format(args['username'])
                self.data = model.GetPassword()
            else:
                self.message = "{0} wrong password".format(args['username'])
        return self.GetResponse()
# ========== select all user resource ==========
class UserSelectAll(BaseResource):
    def __init__(self):
        super().__init__()
    def post(self):
        args = self.parser.parse_args()
        model = UserModel.SelectAllFromDB()
        json_data_list=[]
        if isinstance(model, tuple):
            for line in model:
                json_data={}
                json_data["id"]=line[0]
                json_data["person_id"]=line[1]
                json_data["name"]=line[2]
                json_data["department"]=line[3]
                json_data["role"]=line[4]
                json_data["on_board"]=line[5]
                json_data["username"]=line[6]
                json_data["email"]=line[8]
                json_data_list.append(json_data)
            self.data=json_data_list
        else:
            self.message = "not data"
        return self.GetResponse()
    
# ========== 註冊帳號填寫word匯出 ==========
class UserWordInsert(SendBaseResource):
    def __init__(self):
        super().__init__(self)
        self.parser.add_argument('name', required=True, help="使用者姓名")
#         self.parser.add_argument('job', help="職稱")
        self.parser.add_argument('department', required=True, help="單位")
        self.parser.add_argument('email', required=True, help="email")
#         self.parser.add_argument('phone', required=True, help="phone")
        self.parser.add_argument('date', required=True, help="申請日期")
        self.parser.add_argument('username', required=True, help="帳號")
    def post(self):
        args = self.parser.parse_args()
        doc = Document('resources/test/申請單.docx') 
        tables = doc.tables
        table = tables[0]
        table.cell(1,4).text = args['name']
#         table.cell(1,7).text = args['job']
        table.cell(2,3).text = args['department']
        table.cell(2,7).text = args['email']
#         table.cell(3,3).text = args['phone']
        table.cell(3,7).text = args['date']
        table.cell(4,3).text = "差勤管理系統"
        table.cell(5,3).text = "差勤紀錄檢視，請假申請"
        table.cell(7,3).text = args['username']
        stream = BytesIO()
        doc.save(stream)
        stream.seek(0)
        #doc.save('/home/shuochen/Documents/punch_card_api/flask/notebook/resources/test/申請書{0}.docx'.format(args['name']))
        return self.GetWordResponse("申請書{0}".format(args['name']), stream)