package com.appli.Mysql;


//https://androidjson.com/android-php-insert-display-select-update-delete/

// https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

// https://dzone.com/articles/mobile-app-tutorial-meeting

// https://www.codeproject.com/Articles/800703/Connecting-your-Android-app-to-your-WAMP-server

// https://androidprogramz.blogspot.fr/2012/07/connect-mysql-database-from-android.html

// https://www.journaldev.com/12607/android-login-registration-php-mysql

//http://moinur-rahman.blogspot.fr/2012/02/connection-between-android-app-and.html

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.util.Log;





import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.appli.patoche.R;

/*

public class JSONUseActivity extends Activity
{

    EditText byear;   // To take birthyear as input from user
    Button submit;
    TextView tv;      // TextView to show the result of MySQL query
    String returnString;   // to store the result of MySQL query after decoding JSON

    /** Called when the activity is first created. */
/*
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
/*
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()

                .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread

                .penaltyLog().build());
*/

/*
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);  // doit être definie

        byear = (EditText) findViewById(R.id.editText1);
        submit = (Button) findViewById(R.id.submitbutton);
        tv = (TextView) findViewById(R.id.showresult);

        // define the action when user clicks on submit button
        submit.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                // declare parameters that are passed to PHP script i.e. the name "birthyear" and its value submitted by user
                ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

                // define the parameter
                postParameters.add(new BasicNameValuePair("birthyear", byear.getText().toString()));
                String response = null;

                // call executeHttpPost method passing necessary parameters

                try
                {
                    response = Mysql01.executeHttpPost(
                    //"http://129.107.187.135/CSE5324/jsonscript.php", // your ip address if using localhost server
                    "http://omega.uta.edu/~kmr2464/jsonscript.php",  // in case of a remote server
                    postParameters);

                    // store the result returned by PHP script that runs MySQL query
                    String result = response.toString();

                    //parse json data

                    try
                    {
                        returnString = "";
                        JSONArray jArray = new JSONArray(result);

                        for(int i=0;i<jArray.length();i++)
                        {
                            JSONObject json_data = jArray.getJSONObject(i);
                            Log.i("log_tag","id: "+json_data.getInt("id")+
                                    ", name: "+json_data.getString("name")+
                                    ", sex: "+json_data.getInt("sex")+
                                    ", birthyear: "+json_data.getInt("birthyear")
                            );

                            //Get an output to the screen
                            returnString += "\n" + json_data.getString("name") + " -> "+ json_data.getInt("birthyear");
                        }
                    }

                    catch(JSONException e)
                    {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                    }

                    try
                    {
                        tv.setText(returnString);
                    }
                    catch(Exception e)
                    {
                        Log.e("log_tag","Error in Display!" + e.toString());;
                    }
                }

                catch (Exception e)
                {
                    Log.e("log_tag","Error in http connection!!" + e.toString());
                }
            }
        });
    }
}

/************************************************/
/*
public class Mysql01 {

    /** The time it takes for our client to timeout */
//    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
//    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
/*
    private static HttpClient getHttpClient()
    {
        if (mHttpClient == null)
        {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }

        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the specified
     * parameters.
     *
     //* @param url
     *            The web address to post the request to
     //* @param postParameters
     *            The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
/*
    public static String executeHttpPost(String url,  ArrayList<NameValuePair> postParameters) throws Exception
    {
        BufferedReader in = null;

        try
        {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");

            while ((line = in.readLine()) != null)
            {
                sb.append(line + NL);
            }

            in.close();

            String result = sb.toString();
            return result;
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    Log.e("log_tag", "Error converting result "+e.toString());
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url
     *            The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
/*
    public static String executeHttpGet(String url) throws Exception
    {
        BufferedReader in = null;

        try
        {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");

            while ((line = in.readLine()) != null)
            {
                sb.append(line + NL);
            }

            in.close();

            String result = sb.toString();
            return result;
        }

        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    Log.e("log_tag", "Error converting result "+e.toString());
                    e.printStackTrace();
                }
            }
        }
    }
}

*/
