package com.yihu.hos.broker.controllers;

import com.yihu.hos.core.constants.ExceptionConstant;
import com.yihu.hos.core.exception.ESBException;
import com.yihu.hos.broker.models.GatewayRequestResult;
import com.yihu.hos.broker.models.GatewayResponseResult;
import com.yihu.hos.broker.services.GatewayService;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;

@RestController
@RequestMapping("/esb")
public class GatewayController {
    private final GatewayService gatewayService;

    @Autowired
    public GatewayController(GatewayService gatewayService) {
        this.gatewayService = gatewayService;
    }

    @RequestMapping(value = "/gateway", method = RequestMethod.POST)
    public void transfer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        Writer writer = response.getWriter();
        response.setCharacterEncoding("UTF-8");
        String returnString;

        String resultData;
        GatewayRequestResult gatewayRequestResult = new GatewayRequestResult();
        try {
            BeanUtils.populate(gatewayRequestResult, request.getParameterMap());
            //---end
            gatewayService.paramsIsNotNull(gatewayRequestResult.getApi());
            resultData = gatewayService.getResultData(gatewayRequestResult);
            returnString = resultData;
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof ESBException) {
                ESBException esbException = (ESBException) e;
                returnString = JSONObject.fromObject(GatewayResponseResult.getError(esbException.getExceptionCode(), esbException.getExceptionMessage())).toString();
            } else {
                returnString = JSONObject.fromObject(GatewayResponseResult.getError(ExceptionConstant.EHREXCEPTION_SYSTEMEXCEPTION, ExceptionConstant.EHREXCEPTION_SYSTEMEXCEPTION_MESSAGE)).toString();
            }
        }
        writer.write(returnString);
        writer.flush();
        writer.close();
    }
}
