package com.cretin.webservices.helper.translate;

import com.cretin.webdb.self.BaiduTranslateInfoModel;
import com.cretin.webservices.helper.UserAgentInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.Map;

class HttpGet {
    public static BaiduTranslateInfoModel get(String host, Map<String, String> params, RestTemplate restTemplate) {
        restTemplate.setInterceptors(Collections.singletonList(new UserAgentInterceptor()));
        try {
            String sendUrl = getUrlWithQueryString(host, params);
            return restTemplate.getForEntity(
                    sendUrl, BaiduTranslateInfoModel.class).getBody();
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if ( params == null ) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if ( url.contains("?") ) {
            builder.append("&");
        } else {
            builder.append("?");
        }

        int i = 0;
        for ( String key : params.keySet() ) {
            String value = params.get(key);
            if ( value == null ) { // 过滤空的key
                continue;
            }

            if ( i != 0 ) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(value);

            i++;
        }
        return builder.toString();
    }
}
