from base_resource import BaseResource
from mysql_model import ServerModel

# ========== 新增伺服器資源 ==========
class ServerInsert(BaseResource):
    def __init__(self):
        super().__init__()
        self.parser.add_argument('id')
        self.parser.add_argument('host')
        self.parser.add_argument('port')
    def post(self):
        args = self.parser.parse_args()
        model = ServerModel.FromDB(args['id'])
        if not model.isExist:
            model.SetHost(args['host'])
            model.SetPort(args['port'])
            if model.InsertToDB():
                self.message = "Server {0} insert to database at {1}".format(args['id'], model.GetNow())
            else:
                self.message = "Server {0} insert to database failed".format(args['id'])
        else:
            self.message = "Server {0} is exist in database".format(args['id'])
        return self.GetResponse()
# ========== 更新伺服器資源 ==========
class ServerUpdate(BaseResource):
    def __init__(self):
        super().__init__()
        self.parser.add_argument('id')
        self.parser.add_argument('host')
        self.parser.add_argument('port')
    def post(self):
        args = self.parser.parse_args()
        model = ServerModel.FromDB(args['id'])
        if model.isExist:
            model.SetHost(args['host'])
            model.SetPort(args['port'])
            if model.UpdateToDB():
                self.message = "Server {0} update data at {1}".format(args['id'], model.GetNow())
            else:
                self.message = "Server {0} update failed".format(args['id'])
        else:
            self.message = "Server {0} isn't exist in database".format(args['id'])
        return self.GetResponse()
# ========== 刪除伺服器資源 ==========
class ServerDelete(BaseResource):
    def __init__(self):
        super().__init__()
        self.parser.add_argument('id')
    def post(self):
        args = self.parser.parse_args()
        model = ServerModel.FromDB(args['id'])
        if model.isExist:
            if model.DeleteFromDB():
                self.message = "Server {0} delete at {1}".format(args['id'], model.GetNow())
            else:
                self.message = "Server {0} delete failed".format(args['id'])
        else:
            self.message = "Server {0} isn't exist in database".format(args['id'])
        return self.GetResponse()