package com.example.patrice.request_to_server;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;

import javax.net.ssl.HttpsURLConnection;

// https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/  a voir

// https://blog.dahanne.net/2009/08/16/how-to-access-http-resources-from-android/

// http://www.androidsnippets.com/http-requests-with-java-api-urlconnection.html

// https://maker.pro/education/how-to-get-started-with-iot-using-raspberry-pi-and-putty-part-2

/*************   PHP communication  */
// http://androidcss.com/android/android-php-mysql-login-tutorial/    communication avec php

// http://androidcss.com/android/android-search-view-php-mysql/

// http://androidcss.com/android/android-login-form-material-design/

// http://androidcss.com/android/android-fetch-php-without-library/

    // http://wptrafficanalyzer.in/blog/android-sending-and-receiving-data-from-remote-server-using-intentservice/ php bien a voir

    // https://www.coderefer.com/android-upload-file-to-server/

    //http://www.cuelogic.com/blog/android-code-to-upload-download-large-files-to-server-2/

    // http://androidlift.info/2015/09/21/android-web-service-example/

    // https://nettport.com/en/android/foto_video_and_audio/image_upload_from_android_to_php_server.php

    // https://kosalgeek.com/connect-android-php-mysql-generic-asynctask/

    // http://blog.hackerkernel.com/2015/11/30/android-upload-image-to-server/
    

    //URL = http:// serveur /script?paramètres

// get pour faire une requete
// post pour envoyer des datas

public class MainActivity extends AppCompatActivity {

    TextView content_txt;
    TextView textPHP;
    EditText un, deux, trois;
    String Name, Email, Login;

    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;

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

        content_txt    =   (TextView)findViewById( R.id.simpleTextView );
        textPHP = (TextView) findViewById(R.id.textPHP);
        un      =   (EditText)findViewById(R.id.un);
        deux      =   (EditText)findViewById(R.id.deux);
        trois      =    (EditText)findViewById(R.id.trois);

        Button save = (Button)findViewById(R.id.btn);

        save.setOnClickListener(new Button.OnClickListener(){

            public void onClick(View v)
            {
                try{

                    // CALL GetText method to make post method call
                    //new SendPostRequest().execute();
                    //new SendGetRequest().execute();

                    Name = un.getText().toString();

                    new AsyncRetrieve().execute();

                    //GetText();
                }
                catch(Exception ex)
                {
                   // content.setText(" url exeption! " );
                }
            }
        });
    }

    // Create GetText Metod
    public  void  GetText()  throws UnsupportedEncodingException
    {
        // Get user defined values
        Name = un.getText().toString();
        Email   = deux.getText().toString();
        Login   = trois.getText().toString();


        // Create data variable for sent values to server

        String data = URLEncoder.encode("name", "UTF-8")
                + "=" + URLEncoder.encode(Name, "UTF-8");

        data += "&" + URLEncoder.encode("email", "UTF-8") + "="
                + URLEncoder.encode(Email, "UTF-8");

        data += "&" + URLEncoder.encode("user", "UTF-8")
                + "=" + URLEncoder.encode(Login, "UTF-8");

        String text = "";
        BufferedReader reader=null;



        // Send data
        try
        {
            // Defined URL  where to send data
            URL url = new URL("http://analog-design.net/WORKAREA/WEBSITE/Codebar/new_httppost.php");

            // Send POST data request
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream out = null;

            out = new BufferedOutputStream(conn.getOutputStream());


            BufferedWriter writer = new BufferedWriter (new OutputStreamWriter(out, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            out.close();




//            URLConnection conn = url.openConnection();
//            conn.setDoOutput(true);
//            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//            wr.write( data );
//            wr.flush();

            // Get the server response

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                // Append server response in string
                sb.append(line + "\n");
            }


            text = sb.toString();
        }
        catch(Exception ex)
        {

        }
        finally
        {
            try
            {

                reader.close();
            }

            catch(Exception ex) {}
        }

        // Show response on activity
        //content.setText( text  );

    }


    /**************************************/

    public class SendPostRequest extends AsyncTask<String, Void, String>
    {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0)
        {

            try
            {

                URL url = new URL("http://analog-design.net/WORKAREA/WEBSITE/Codebar/new_httppost.php"); // here is your URL path

                JSONObject postDataParams = new JSONObject();
                postDataParams.put("name", "abc");
                postDataParams.put("email", "abc@gmail.com");
                Log.e("params",postDataParams.toString());

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));
                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK)
                {
                    BufferedReader in=new BufferedReader(new InputStreamReader( conn.getInputStream() ));

                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null)
                    {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else
                {
                    return new String("false : "+responseCode);
                }
            }

            catch(Exception e)
            {
                return new String("Exception: " + e.getMessage());
            }

        }

        @Override
        protected void onPostExecute(String result)
        {
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        }
    }


    /**************************************************/

    public class SendGetRequest extends AsyncTask<String, Void, String>
    {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0)
        {

            try
            {

                URL url = null; // here is your URL path

                try
                {
                    url = new URL("http://analog-design.net/WORKAREA/WEBSITE/Codebar/new_http_get.php");
                }

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

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("GET");

                conn.setInstanceFollowRedirects(true);
                conn.setUseCaches(false);

                int resultServer = conn.getResponseCode();
                if (resultServer == HttpURLConnection.HTTP_OK)
                {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int read = 0;
                    while ((read = is.read()) != -1)
                    {
                        bos.write(read);
                    }
                    byte[] result = bos.toByteArray();
                    bos.close();
                    String data = new String(result);

                    //content_txt.setText(data);
                    String res = data;
                }

                else
                {
                    //txtResult.setText("Error Code : " + resultServer);
                    String res = "plouf";
                }

                conn.disconnect();

            }

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

            return("toto");
        }

        @Override
        protected void onPostExecute(String result)
        {
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        }
    }


    public String getPostDataString(JSONObject params) throws Exception
    {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext())
        {
            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }

        return result.toString();
    }


    /*********************************/

    private class AsyncRetrieve extends AsyncTask<String, String, String>
    {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

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

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();
        }

        // This method does not interact with UI, You need to pass result to onPostExecute to display
        @Override
        protected String doInBackground(String... params)
        {
            try
            {
                // Enter URL address where your php file resides
                //url = new URL("http://analog-design.net/WORKAREA/WEBSITE/Codebar/exemple.php");


                url = new URL("http://analog-design.net/WORKAREA/WEBSITE/Codebar/php_com.php?var=" + Name);

//                url = Constants.SERVER_URL + "/get_capital.php?country=" + country;



            }
            catch (MalformedURLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }

            try
            {

                // Setup HttpURLConnection class to send and receive data from php
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            }

            catch (IOException e1)
            {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try
            {
                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK)
                {
                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null)
                    {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                }
                else
                {
                    return ("unsuccessful");
                }

            }
            catch (IOException e)
            {
                e.printStackTrace();
                return e.toString();
            }
            finally
            {
                conn.disconnect();
            }


        }

        // this method will interact with UI, display result sent from doInBackground method
        @Override
        protected void onPostExecute(String result)
        {

            pdLoading.dismiss();
            if(result.equals("Success! This message is from PHP"))
            {
                textPHP.setText(result.toString());
            }
            else
            {
                // you to understand error returned from doInBackground method
                Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}