package com.example.patrice.http01;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//import static com.example.patrice.http01.fileUploadDownload.uploadFileToServer;

// http://androidcss.com/android/android-php-mysql-login-tutorial/
// https://github.com/androidcss/login-system-with-android-php-and-mysql-using-httpurlconnection/tree/master/android/MyApplication/app/src/main/java/com/guru/login


/********************************************/
/*
 download fichier  server -> android

 upload fichier    server <- android
*/
public class MainActivity extends AppCompatActivity
{

    Button btn_http;
    Button btn_activity02;
    Button btn_activity03;
    Button btn_activity06;
    Button btn_activity07;
    Button btn_activity08;
    Button btn_activity09;
    Button btn_activity10;
    Button btn_activity11;
    Button btn_activity12;
    Button btn_activity13;

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds

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

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

        btn_http = (Button) findViewById(R.id.btn_http);
        btn_activity02 = (Button) findViewById(R.id.btn_activity02);
        btn_activity03 = (Button) findViewById(R.id.btn_activity03);

        btn_activity06 = (Button) findViewById(R.id.btn_activity06);
        btn_activity07 = (Button) findViewById(R.id.btn_activity07);
        btn_activity08 = (Button) findViewById(R.id.btn_activity08);
        btn_activity09 = (Button) findViewById(R.id.btn_activity09);
        btn_activity10 = (Button) findViewById(R.id.btn_activity10);
        btn_activity11 = (Button) findViewById(R.id.btn_activity11);
        btn_activity12 = (Button) findViewById(R.id.btn_activity12);
        btn_activity13 = (Button) findViewById(R.id.btn_activity13);


        btn_http.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                //Intent myIntent = new Intent(MainActivity.this, NewActivity.class);
                //startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();

                // Initialize  AsyncLogin() class with email and password
                String username = "patoche";
                String password = "rainbow";

                new AsyncLogin().execute(username,password);

            }
        });

        btn_activity02.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, http02.class);
                startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });


        btn_activity03.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, http03.class);
                startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });

        btn_activity06.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, http06.class);
                startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });

        btn_activity07.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, http07.class);
                startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });


        btn_activity08.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, http08.class);
                startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });


        btn_activity09.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, http09.class);
                startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });

        btn_activity10.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, upload01.class);
                startActivity(myIntent);
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });

        btn_activity11.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                //Intent myIntent = new Intent(MainActivity.this, upload01.class);
                //startActivity(myIntent);

                fileUploadDownload instance = new fileUploadDownload();

                instance.uploadFileToServer("receive.jpg", "http://analog-design.net/WORKAREA/WEBSITE/Codebar/upload01.php"  );

                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
            }
        });

        btn_activity12.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                //Intent myIntent = new Intent(MainActivity.this, upload02.class);
                //startActivity(myIntent);
                //Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();

                tools01 id = new tools01();
                //id.accessWebService();


                id.toto();

                //id.Download("http://www.analog-design.net/MP3/listing.txt");

            }
        });

        btn_activity13.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent myIntent = new Intent(MainActivity.this, activity02.class);
                startActivity(myIntent);

            }
        });




    }

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

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

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

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your php file resides
                String adresse = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/http_server.php";

                //url = new URL("http://localhost/test/login.inc.php");
                url = new URL(adresse);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "exception";
            }
            try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");

                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

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

            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 "exception";
            } finally {
                conn.disconnect();
            }


        }

        /**/
        @Override
        protected void onPostExecute(String result)
        {
            pdLoading.dismiss();

            //Toast.makeText(MainActivity.this,result, Toast.LENGTH_LONG).show();

            if(result.equalsIgnoreCase("true"))
            {
               // Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
                //startActivity(intent);
                //MainActivity.this.finish();
                Toast.makeText(MainActivity.this, "Youpi !!!!", Toast.LENGTH_LONG).show();
            }

            else if (result.equalsIgnoreCase("false"))
            {
                // If username and password does not match display a error message
                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();
            }

            else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful"))
            {
                Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
            }
        }
		/**/

    }
}
