package com.example.patrice.notification_message;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;

// https://www.simplifiedcoding.net/firebase-cloud-messaging-android/  php mysql
// https://www.androidhive.info/2016/10/android-push-notifications-using-firebase-cloud-messaging-fcm-php/8/
// https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //defining views
    private Button buttonDisplayToken;
    private TextView textViewToken;

    TextView tv_utilisateur;
    TextView tv_lock_user;

    JSONParser jParser = new JSONParser();

    private static String url_add_token_db = "http://analog-design.net/WORKAREA/WEBSITE/douche/reception.php";

    public static final String key_nom_utilisateur = "nom_utilisateur";

    String nom_uilisateur = null;


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

        getSupportActionBar().setTitle("  Busy ? ");
        getSupportActionBar().setLogo(R.drawable.shower);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        tv_lock_user = (TextView) findViewById(R.id.tv_lock_user);
        tv_utilisateur = (TextView) findViewById(R.id.tv_utilisateur);

        //getting views from xml
//        textViewToken = (TextView) findViewById(R.id.textViewToken);
//        buttonDisplayToken = (Button) findViewById(R.id.buttonDisplayToken);

        //adding listener to view
//        buttonDisplayToken.setOnClickListener(this);

        //new SendPostRequest().execute();

        Toast.makeText(getApplicationContext(), "Patoche software - Debug on going", Toast.LENGTH_LONG).show();


        SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("PREFERENCE", 0); // 0 - for private mode
        Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE) .getBoolean("isFirstRun", true);
        //   RESET pour le debug
        //   getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isFirstRun", true).commit();

        // premier run on doit valider l'enregristrement du client
        if (isFirstRun)
        {
            startActivity(new Intent(MainActivity.this, appairage.class));
        }

        nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);
        tv_utilisateur.setText(nom_uilisateur + " connected");


    }

    @Override
    public void onClick(View view) {
        if (view == buttonDisplayToken) {
            //getting token from shared preferences
            String token = SharedPrefManager.getInstance(this).getDeviceToken();

            //if token is not null
            if (token != null) {
                //displaying the token
                textViewToken.setText(token);

                new update_database().execute(token);

            } else {
                //if token is null that means something wrong
                textViewToken.setText("Token not generated");
            }
        }
    }


    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/douche/reception.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 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                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 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();
    }


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

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

        @Override
        protected String doInBackground(String... args)
        {

            String token = args[0];

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("token", token));
            params.add(new BasicNameValuePair("user", "delpy"));

            JSONObject json = jParser.makeHttpRequest(url_add_token_db, "POST", params);

            Log.d("Create Response", json.toString());

            String reponse = null;

            try {
                //int success = json.getInt(TAG_SUCCESS);
                String msg = json.getString("success");

                if (msg.equals("1")) {
                    reponse = "OK";
                } else {
                    reponse = "FAIL";
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return (reponse);

        }

        @Override
        protected void onPostExecute(String result)
        {
            if (result.equals("OK")) {
                Toast.makeText(getApplicationContext(), "Token ajouter avec succés", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Erreur de traitement : Sauvegarde impossible !", Toast.LENGTH_LONG).show();
            }
        }
    }


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /************************************************************************/
    // menu dans la l'action bar
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent i;

        switch (item.getItemId()) {
            case R.id.item1:
                i = new Intent(getApplicationContext(), aide.class);
                startActivity(i);
                break;

            case R.id.item2:
                i = new Intent(getApplicationContext(), token.class);
                startActivity(i);
                break;

            case R.id.item3:
                about();
                break;

            case android.R.id.home:
                quitter_confirmation();
                return true;
        }


        return super.onOptionsItemSelected(item);
    }

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

    public void about()
    {
        final Dialog dialog = new Dialog(MainActivity.this);

        dialog.setContentView(R.layout.about_layout);
        dialog.setTitle("About:");
        dialog.show();

        Button dialogCloseButton = (Button) dialog.findViewById(R.id.close_button);

        dialogCloseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }

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

    public void quitter_confirmation()
    {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        alertDialogBuilder.setTitle("Confirmation");

        alertDialogBuilder
                .setMessage("Quitter l'appli ?.")
                .setCancelable(false)
                .setPositiveButton("Oui", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Toast.makeText(MainActivity.this, "A bientôt ...", Toast.LENGTH_SHORT).show();
                        MainActivity.this.finishAffinity();
                        System.exit(0);
                    }
                })

                .setNegativeButton("Non", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

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

    public void onBackPressed()
    {
        quitter_confirmation();
    }

    /************************************************************************/
}