from base_resource import BaseResource
from mysql_model import PersonTypeModel

# ========== 新增使用者資源 ==========
class PersonTypeInsert(BaseResource):
    def __init__(self):
        super().__init__("InsertPersonType")
        self.parser.add_argument('name', required=True, help="上限 10 字")
    def post(self):
        args = self.parser.parse_args()
        model = PersonTypeModel.FromName(args['name'])
        if not model.isExist:
            model.SetName(args['name'])
            if model.InsertToDB(self.log.SetMessage):
                self.message = "{0} inserted".format(args['name'], model.GetNow())
            else:
                self.message = "{0} insert failed".format(args['name'])
        else:
            self.message = "{0} is exist in database".format(args['name'])
        return self.GetResponse()
# ========== 更新使用者資源 ==========
class PersonTypeUpdate(BaseResource):
    def __init__(self):
        super().__init__("UpdatePersonType")
        self.parser.add_argument('id')
        self.parser.add_argument('name')
    def post(self):
        args = self.parser.parse_args()
        model = PersonTypeModel.FromDB(args['id'])
        if model.isExist:
            model.SetName(args['name'])
            if model.UpdateToDB(self.log.SetMessage):
                self.message = []
                if model.HasChangeName():
                    self.message.append(
                        "Name: {0} -> {1}".format(model.GetOldName(), model.GetName())
                    )
                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 PersonTypeDelete(BaseResource):
    def __init__(self):
        super().__init__("DeletePersonType")
        self.parser.add_argument('id')
    def post(self):
        args = self.parser.parse_args()
        model = PersonTypeModel.FromDB(args['id'])
        if model.isExist:
            if model.DeleteFromDB(self.log.SetMessage):
                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()