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

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.Certificate;

import kz.arta.synergy.workflow.mobile.android.authorization.GetCertificate;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.utils.Logger;

/**
 * Created by neox on 04.04.14.
 * Простой get запрос
 */
public class SendGetRequest extends AsyncTask<Void, Void, String> {

    /**
     * Таймаут
     */
    public static final int TIMEOUT = 60000;
    /**
     * Менеджер для работы с сертификатом
     */
    private static GetCertificate getCertificate;
    /**
     * Данные пользователя
     */
    private Person person;
    /**
     * URL
     */
    private String url;

    public SendGetRequest(Person person) {
        this.person = person;
    }

    public SendGetRequest(String url, Person person) {
        this.url = url;
        this.person = person;
    }

    /**
     * Метод используется для валидации адреса сервера
     *
     * @param url адрес сервера
     * @return результат выполнения метода
     */
    public static String request(String url) {
        String line;
        StringBuffer result;
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(SendGetRequest.TIMEOUT);
            connection.setRequestProperty("Accept", "application/json; charset=utf-8");
            connection.setReadTimeout(SendGetRequest.TIMEOUT);
            InputStream content = connection.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            result = new StringBuffer();
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            connection.disconnect();
            return result.toString();
        } catch (Exception e) {
            if (connection != null) {
                try {
                    connection.disconnect();
                    return null;
                } catch (Exception exc) {
                    return null;
                }
            } else {
                return null;
            }
        }
    }

    /**
     * Метод возвращает HttpURLConnection для указанного пользователя и url
     *
     * @param person данные пользователя
     * @param url    url до апи метода
     * @return HttpURLConnection
     */
    public static HttpURLConnection getConnection(Person person, String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(person.getHost() + url).openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(SendGetRequest.TIMEOUT);
            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.setDoInput(true);
            conn.setDoOutput(true);
            return conn;
        } catch (Exception exc) {
            return null;
        }
    }

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

    /**
     * Обычный get запрос на сервер
     *
     * @param url url до апи метода
     * @return результат выполнения метода
     */
    public String requestGET(String url) {
        String line;
        StringBuffer result;
        HttpURLConnection connection = null;
        try {
            String u = (this.url == null ? url : person.getHost() + url);
            Logger.v(u);
            if (u.contains("https://")) {
                if (getCertificate == null) {
                    getCertificate = new GetCertificate();
                }
                Certificate cert = getCertificate.getCert(person.getShortHost());
                if (cert == null) {
                    return null;
                }
                getCertificate.save(cert);
            }
            connection = (HttpURLConnection) new URL(u).openConnection();
            connection.setReadTimeout(SendGetRequest.TIMEOUT);
            connection.setConnectTimeout(SendGetRequest.TIMEOUT);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json; charset=utf-8");
            String basicAuth = "Basic " + new String(Base64.encode((person.getAuth()).getBytes(), Base64.NO_WRAP));
            connection.setRequestProperty("Authorization", basicAuth);
            InputStream content = connection.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            result = new StringBuffer();
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (java.net.SocketTimeoutException exc) {
            return null;
        } catch (Exception exc) {
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}