package com.example.patrice.http_get_post01;

import android.os.AsyncTask;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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 android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

// https://www.survivingwithandroid.com/2013/06/android-apache-http-client.html

// http://abhiandroid.com/java/hashmap

public class MainActivity extends Activity
{
    TextView res;
    EditText txtA, txtB;
    Button getData;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtA = (EditText)findViewById(R.id.txtA);
        txtB = (EditText)findViewById(R.id.txtB);
        res = (TextView)findViewById(R.id.txtResult);
        getData = (Button) findViewById(R.id.btnGetData);

        // Perform action on click
        getData.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String url = "http://www.analog-design.net/WORKAREA/WEBSITE/Codebar/getHttpPost.php";
                url = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/getHttpPost.php";

                //List<NameValuePair> params = new ArrayList<NameValuePair>();
                //params.add(new BasicNameValuePair("strA", txtA.getText().toString()));
                //params.add(new BasicNameValuePair("strB", txtB.getText().toString()));
                //String resultServer  = getHttpPost(url,params);
                //result.setText(resultServer);

                SendHttpRequestTask t = new SendHttpRequestTask();
                String[] params = new String[]{url, txtA.getText().toString(), txtB.getText().toString()};
                t.execute(params);

            }
        });

    }


    private class SendHttpRequestTask extends AsyncTask<String, Void, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            String url = params[0];
            String val1 = params[1];
            String val2 = params[2];

            String data = sendHttpRequest(url, val1, val2);
            System.out.println("Data ["+data+"]");
            return data;
        }

        @Override
        protected void onPostExecute(String aaresult)
        {
            String toto = aaresult;
            res.setText(aaresult);
        }

    }

    private String sendHttpRequest(String url, String val1, String val2)
    {
        StringBuffer buffer = new StringBuffer();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("strA", val1));
        params.add(new BasicNameValuePair("strB", val2));

        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try
        {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                HttpResponse response = client.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();

                if (statusCode == 200)
                { // Status OK
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String line;

                    while ((line = reader.readLine()) != null)
                    {
                        str.append(line);
                    }
                }
                else
                {
                    Log.e("Log", "Failed to download result..");
                }
        }

        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }

        catch (IOException e)
        {
            e.printStackTrace();
        }
        return str.toString();

    }
/*
    @Override
    protected byte[] doInBackground(String... params)
    {

        String url = params[0];
        String name = params[1];

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        paramList.add(new BasicNameValuePair("name", name));
        byte[] data = null;

        try {
            post.setEntity(new UrlEncodedFormEntity(paramList));
            HttpResponse resp = client.execute(post);
            InputStream is = resp.getEntity().getContent();
            int contentSize = (int) resp.getEntity().getContentLength();
            System.out.println("Content size ["+contentSize+"]");
            BufferedInputStream bis = new BufferedInputStream(is, 512);

            data = new byte[contentSize];
            int bytesRead = 0;
            int offset = 0;

            while (bytesRead != -1 &amp;&amp; offset &lt; contentSize) {
                bytesRead = bis.read(data, offset, contentSize - offset);
                offset += bytesRead;
            }
        }
        catch(Throwable t) {
            // Handle error here
            t.printStackTrace();
        }

        return data;


    }
  */


    public String getHttpPost(String url,List<NameValuePair> params) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Status OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

}