package kz.arta.synergy.workflow.mobile.android.common.requests;

import android.os.AsyncTask;
import android.util.Base64;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import kz.arta.synergy.workflow.mobile.android.common.models.Person;

/**
 * Created by neox on 24.12.14.
 * Отправка текущего местоположения
 */
public class Positions extends AsyncTask<Void, Void, String> {

    /**
     * Пользователь
     */
    private Person person;

    /**
     * Данные, которые будут отправлены на сервер
     */
    private String data;

    public Positions(Person person, String data) {
        this.person = person;
        this.data = data;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    private String send() {
        try {
            URL url = new URL(person.getHost() + "rest/api/events/create");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json; charset=utf-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String basicAuth = "Basic " + new String(Base64.encode(person.getAuth().getBytes(), Base64.NO_WRAP));
            conn.setRequestProperty("Authorization", basicAuth);
            conn.setUseCaches(false);
            conn.setConnectTimeout(10000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            DataOutputStream request = new DataOutputStream(conn.getOutputStream());
            request.writeBytes("eventName=" + URLEncoder.encode("event.ext.gps", "utf-8") + "&");
            request.writeBytes("eventMsg=" + URLEncoder.encode(data, "utf-8") + "&");
            request.flush();
            request.close();
            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    protected String doInBackground(Void... params) {
        return send();
    }

}
