package com.house365.web;

import com.house365.common.util.RestTemplateBean;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取远程JSON请求字符串
 * Created by 365 on 2015/3/5.
 */
@Controller("remoteJson")
@RequestMapping("remoteJson")
public class RemoteJsonController {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(RemoteJsonController.class);

    /**
     * 获取JSON内容
     *
     * @param request 请求对象
     * @return JSON内容
     */
    @RequestMapping(value = "getJson", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getJson(HttpServletRequest request, String city) {
        String result = null;
        Map<String, String[]> parameterMap = new HashMap<String, String[]>();
        parameterMap.putAll(request.getParameterMap());
        String[] cities = parameterMap.get("city");
        if (ArrayUtils.isEmpty(cities) || StringUtils.isEmpty(cities[0])) {
            parameterMap.put("city", new String[]{city});
        }
        String[] urls = parameterMap.remove("url");
        if (ArrayUtils.isNotEmpty(urls)) {
            final String url = urls[0];
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()[0]));
            }
            try {
                result = RestTemplateBean.doGet(url, params);
            } catch (Exception ex) {
                LOGGER.error(ex.getMessage(), ex);
            } finally {
                return result;
            }
        } else {
            return result;
        }
    }
}
