package com.hesias.geekquote.geekquote.asynctasks;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

import com.hesias.geekquote.geekquote.activities.QuoteListActivity;
import com.hesias.geekquote.geekquote.tools.ConnectivityHelper;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;

public class RestAsynck extends AsyncTask {

    private Activity act;

    public RestAsynck(Activity act) {
        this.act = act;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d("HESIAS", "onPreExec");
    }

    @Override
    protected String doInBackground(Object[] objects) {
        HttpURLConnection client = null;
        String result = null;
        Log.d("HESIAS", "onExec");
        //Check if network is available
        if(ConnectivityHelper.isNetworkAvailable(this.act)) {
            try {
                URL url = new URL("http://steve-colinet.fr/");
                client = (HttpURLConnection) url.openConnection();
                //You can use HttpsURLConnection to https
                // and client.setHostnameVerifier(DO_NOT_VERIFY);


                //if GET Method
                client.setRequestMethod("GET");

                //if Methode POST
                //client.setRequestMethod("POST");
                //client.setDoOutput(true);
                //client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                //HashMap<String, String> params = new HashMap<String, String>();
                //params.put("action","login");
                //params.put("login","admin");
                //params.put("password","admin");
                //DataOutputStream dStream = new DataOutputStream(client.getOutputStream());
                //dStream.writeBytes(this.getQuery(params));
                //dStream.flush();
                //dStream.close();


                client.connect();
                StringBuffer sb = new StringBuffer();
                InputStream is = null;

                int response = client.getResponseCode();
                if (response != HttpURLConnection.HTTP_OK) {
                    return null;
                }

                try {
                    is = new BufferedInputStream(client.getInputStream());
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String inputLine = "";
                    while ((inputLine = br.readLine()) != null) {
                        sb.append(inputLine);
                        sb.append("\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    Log.i("HESIAS", "Error reading InputStream");
                    result = null;
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            Log.i("HESIAS", "Error closing InputStream");
                        }
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (client != null) {
                    client.disconnect();
                }
            }
        }
        return result;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        Log.d("HESIAS", "onPostExec");
        ((QuoteListActivity) this.act).onRestReturn(o.toString());
    }

    //Create a string of datas for body request
    private String getQuery(HashMap<String, String>  params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        Iterator myVeryOwnIterator = params.keySet().iterator();
        while(myVeryOwnIterator.hasNext()) {
            String key = (String)myVeryOwnIterator.next();
            String value = (String)params.get(key);
            if (first) {  first = false; }
            else { result.append("&"); }
            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value, "UTF-8"));
        }
        return result.toString();
    }
}
