package com.yihu.hos.broker.services;

import com.yihu.hos.broker.configurations.GatewayConfiguration;
import com.yihu.hos.core.constants.CoreConstant;
import com.yihu.hos.core.constants.ExceptionConstant;
import com.yihu.hos.core.exception.ESBException;
import com.yihu.hos.core.http.HttpClientKit;
import com.yihu.hos.broker.models.GatewayRequestResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author chenweida on 2016/1/27.
 */
@Service
public class GatewayService {
    private final GatewayConfiguration gatewayConfiguration;

    @Autowired
    public GatewayService(GatewayConfiguration gatewayConfiguration) {
        this.gatewayConfiguration = gatewayConfiguration;
    }

    public String getResultData(GatewayRequestResult gatewayRequestResult) throws ESBException {

        String returnData;
        //拼凑出URL
        String url = getUrl(gatewayConfiguration.getIp(), gatewayConfiguration.getPort(), gatewayRequestResult.getApi());
        try {
            Map<String, String> params = getParams(gatewayRequestResult.getParam());

            returnData = HttpClientKit.post(url, params).getBody();
            System.out.print(returnData);
        } catch (Exception e) {
            throw new ESBException(ExceptionConstant.EHREXCEPTION_SYSTEM_TRANSFER, ExceptionConstant.EHREXCEPTION_SYSTEM_TRANSFER_MESSAGE);
        }
        return returnData;
    }

    public void paramsIsNotNull(Object params) throws ESBException {
        if (StringUtils.isEmpty(params)) {
            throw new ESBException(ExceptionConstant.EHREXCEPTION_BUSINESS_PARAMS_EXCEPTION, ExceptionConstant.EHREXCEPTION_BUSINESS_PARAMS_EXCEPTION_MESSAGE);
        }
    }

    private String getUrl(String ip, String port, String api) {
        String url = CoreConstant.HTTP + CoreConstant.COLON + CoreConstant.BACKSLASH +
                CoreConstant.BACKSLASH + ip + CoreConstant.COLON + port +
                CoreConstant.BACKSLASH + api;
        return url;
    }

    private Map<String, String> getParams(String jsonParam) {
        JSONObject object = JSONObject.fromObject(jsonParam);

        Map<String, String> params = new HashMap<>();
        Iterator<?> keys = object.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            String value = object.getString(key);
            params.put(key, value);

        }

        return params;
    }
}
