package ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import ru.yandex.common.util.concurrent.Executors;
import ru.yandex.common.util.concurrent.StoppableExecutorService;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import static ru.yandex.common.util.StringUtils.isEmpty;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 05.06.14
 * Time: 11:05
 */
@Slf4j
public class RequestReporter {

    private String reportUri;

    public void setReportUri(final String reportUri) {
        this.reportUri = reportUri;
    }

    StoppableExecutorService threadPool = Executors.newFixedThreadPool(10, "Result reporter");

    public void report(final String url, final String body, final String result) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(params, 1000);
                DefaultHttpClient client = new DefaultHttpClient(params);
                HttpPost request = new HttpPost(reportUri);
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
                if (!isEmpty(url)) {
                    nameValuePairs.add(new BasicNameValuePair("url", url));
                }
                if (body != null) {
                    nameValuePairs.add(new BasicNameValuePair("body", body));
                }
                nameValuePairs.add(new BasicNameValuePair("result", result));
                try {
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, Charset.forName("utf-8"));
                    entity.setContentEncoding("UTF-8");
                    request.setEntity(entity);
                    client.execute(request);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }
}
