# -*- coding:utf-8 -*-


from model_data_api.model.modelsData_model import ModelsDataManager
from model_data_api.handler.Base_Handler import BaseHandler
from model_data_api.views import *
from utils import JsonUtil
import pandas as pd
from model_data_api.handler.logic import *

app = app()
@app.route('/api/models')
class ModelsDataHandler(BaseHandler):

    def initialize(self):
        self.session = ModelsDataManager()
        pass
    def on_finish(self):
        self.session.close()

    def post(self):
        try:
            name = self.get_argument('models_name',default=None)
            content = self.get_argument('models_content',default='')
            create_name = self.get_argument('models_create_name',default=None)
            el_expression = self.get_argument('models_el_expression',default=None)
            result = add_models_logic(self.session,name,content,create_name,el_expression)
            self.write(JsonUtil.build_json_data(code=result['code'],
                                                message=result['message'],
                                                model_name = name,
                                                model_content =content,
                                                model_el_expression =el_expression,
                                                ))

            self.flush()
            self.finish()
        except ValueError as e:
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Param_Error, JsonUtil.Constants.Msg_Param_Error))
            self.flush()
        except Exception as e:
            # == 报异常，查询失败
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Error, JsonUtil.Constants.Msg_Error))
            self.flush()

    def get(self, *args, **kwargs):
        try:
            models_name = self.get_argument('model_name',default=None)
            result = get_models_logic(self.session,models_name)
            self.write(JsonUtil.build_json_data(code=result['code'],
                                                message=result['message'],
                                                result=result['result'],
                                                models_name = models_name
                                                ))

            self.flush()
            self.finish()
        except ValueError as e:
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Param_Error, JsonUtil.Constants.Msg_Param_Error))
            self.flush()

        except Exception as e:
            # == 报异常，查询失败
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Error, JsonUtil.Constants.Msg_Error))
            self.flush()