package com.aplusinformatique.aplusmanager.Activitys;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.aplusinformatique.aplusmanager.BuildConfig;
import com.aplusinformatique.aplusmanager.R;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.ProgressCallback;

import java.io.File;

public class Activity_Lancement extends AppCompatActivity {
    private static final String aplusmanager_url_version_txt = "http://www.traplus.com/prov/APLUS/DistriMobileV3/AplusManager/version.php";
    private static final String aplusmanager_url_version_apk = "http://www.traplus.com/prov/APLUS/DistriMobileV3/AplusManager/version.apk";
    private static final String aplusmanager_apk_name = "AplusManager.apk";
    private static final String distrimobile_url_version_txt = "http://www.traplus.com/prov/APLUS/DistriMobileV3/DistriMobile/version.php";
    private static final String distrimobile_url_version_apk = "http://www.traplus.com/prov/APLUS/DistriMobileV3/DistriMobile/version.apk";
    private static final String distrimobile_apk_name = "DistriMobile.apk";
    private static final String barcodescanner_url_version_apk = "http://www.traplus.com/prov/APLUS/DistriMobileV3/BarcodeScanner/version.apk";
    private static final String barcodescanner_apk_name = "BarcodeScanner.apk";
    private final static String PACKAGE_NAME = "com.aplusinformatique.aplusmanager";
    private final static int REQUESTCODE_STORAGE_PERMISSION = 1;
    private final Context mContext = this;
    private ProgressDialog progressDialog;

    private static boolean storagePermitted(Activity activity) {

        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&

                ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)

            return true;

        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTCODE_STORAGE_PERMISSION);

        return false;
    }

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

        overridePendingTransition(0, 0);

        progressDialog = new ProgressDialog(Activity_Lancement.this, R.style.ProgressBar);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);

        if (getIntent() != null) {
            if (getIntent().getExtras() != null) {
                if (getIntent().getBooleanExtra("barcodescanner", false)) {
                    telechargerApkBarcodeScanner();
                } else {
                    if (storagePermitted(Activity_Lancement.this)) {
                        checkMAJAplusManager();
                    }
                }
            } else {
                if (storagePermitted(Activity_Lancement.this)) {
                    checkMAJAplusManager();
                }
            }
        } else {
            if (storagePermitted(Activity_Lancement.this)) {
                checkMAJAplusManager();
            }
        }
    }

    private void checkMAJAplusManager() {
        if (isOnline(Activity_Lancement.this)) {
            progressDialog.dismiss();
            progressDialog.setMessage("Vérification de la version de l'application ...");
            progressDialog.show();

            Ion.with(Activity_Lancement.this)
                    .load(aplusmanager_url_version_txt)
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {
                            if (progressDialog.isShowing()) progressDialog.dismiss();

                            if (result != null) {
                                int versioncode = result.get("versioncode").getAsInt();

                                final PackageManager pm = getPackageManager();
                                PackageInfo currentPackageInfo = null;

                                try {
                                    currentPackageInfo = pm.getPackageInfo(PACKAGE_NAME, 0);
                                } catch (PackageManager.NameNotFoundException e1) {
                                    e1.printStackTrace();

                                    finish();
                                    overridePendingTransition(0, 0);
                                }

                                if (currentPackageInfo.versionCode < versioncode) {
                                    telechargerApkAplusManager();
                                } else {
                                    checkMAJDistriMobile();
                                }
                            } else {
                                popupMessageSimple("Veuillez relancer la page ...");
                            }
                        }
                    });
        } else {
            popupMessageSimple("Vous avez besoin d'une connection internet !");
        }
    }

    private void checkMAJDistriMobile() {
        if (isOnline(Activity_Lancement.this)) {
            progressDialog.dismiss();
            progressDialog.setMessage("Vérification de la version de DistriMobile ...");
            progressDialog.show();

            Ion.with(Activity_Lancement.this)
                    .load(distrimobile_url_version_txt)
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {
                            if (progressDialog.isShowing()) progressDialog.dismiss();

                            if (result != null) {
                                Log.d("x", result.toString());

                                String versionname = result.get("versionname").getAsString();

                                PackageInfo pinfo = null;

                                try {
                                    pinfo = getPackageManager().getPackageInfo("com.aplusinformatique.distrimobile_v2", 0);
                                } catch (PackageManager.NameNotFoundException e1) {
                                    e1.printStackTrace();
                                }

                                String distrimobileVersionName = "";

                                if (pinfo != null) distrimobileVersionName = pinfo.versionName;

                                Log.d("xxx", "vc app : " + distrimobileVersionName);
                                Log.d("xxx", "vc json : " + versionname);

                                if (!distrimobileVersionName.equals(versionname)) {
                                    telechargerApkDistriMobile();
                                } else {
                                    Log.d("x", "distrimobile à jour");

                                    finish();
                                    overridePendingTransition(0, 0);

                                    Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.aplusinformatique.distrimobile_v2");

                                    if (launchIntent != null) {
                                        startActivity(launchIntent);
                                    }
                                }
                            }
                        }
                    });
        } else {
            popupMessageSimple("Vous avez besoin d'une connection internet !");
        }
    }

    private void telechargerApkAplusManager() {
        final File downloadedApk = new File(Environment.getExternalStorageDirectory(), aplusmanager_apk_name);

        progressDialog.dismiss();

        progressDialog = new ProgressDialog(Activity_Lancement.this, R.style.ProgressBar);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Téléchargement de la mise à jour de l'application Aplus Manager ...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIndeterminate(false);
        progressDialog.setProgressNumberFormat(null);

        progressDialog.show();

        Log.d("x", "start dl aplus");

        Ion.with(Activity_Lancement.this)
                .load(aplusmanager_url_version_apk)
                .progressDialog(progressDialog)
                .progress(new ProgressCallback() {
                    @Override
                    public void onProgress(long downloaded, long total) {
                        //Log.d("x","avance");

                        System.out.println("" + downloaded + " / " + total);
                    }
                })
                .write(downloadedApk)
                .setCallback(new FutureCallback<File>() {
                    @Override
                    public void onCompleted(Exception e, File file) {
                        Log.d("x", "fin dl aplus");
                        //Log.d("x","exception: "+e);

                        if (progressDialog.isShowing()) progressDialog.dismiss();

                        if (file != null) {
                            try {
                                Log.d("x", "lance installe aplus");

                                finish();
                                overridePendingTransition(0, 0);

//                                Intent intent = new Intent(Intent.ACTION_VIEW);
//                                Uri uri = Uri.fromFile(new File(downloadedApk.getAbsolutePath()));
//                                intent.setDataAndType(uri, "application/vnd.android.package-archive");
//                                startActivity(Intent.createChooser(intent, "Installation de l'application AplusManager"));

                                File fileApk = new File(downloadedApk.getAbsolutePath());
                                InstallFile(fileApk);

                            } catch (Exception ex) {
                                Log.e(getClass().getName(), "L'installation de la mise à jour a échoué", ex);
                                Toast.makeText(getApplicationContext(), "L'installation de la mise à jour a échoué", Toast.LENGTH_SHORT).show();

                                finish();
                                overridePendingTransition(0, 0);
                            }
                        }
                    }
                });
    }

    private void telechargerApkDistriMobile() {
        final File downloadedApk = new File(Environment.getExternalStorageDirectory(), distrimobile_apk_name);

        progressDialog.dismiss();

        progressDialog = new ProgressDialog(Activity_Lancement.this, R.style.ProgressBar);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Téléchargement de la mise à jour de DistriMobile ...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIndeterminate(false);
        progressDialog.setProgressNumberFormat(null);

        progressDialog.show();

        Ion.with(Activity_Lancement.this)
                .load(distrimobile_url_version_apk)
                .progressDialog(progressDialog)
                .progress(new ProgressCallback() {
                    @Override
                    public void onProgress(long downloaded, long total) {
                        System.out.println("" + downloaded + " / " + total);
                    }
                })
                .write(downloadedApk)
                .setCallback(new FutureCallback<File>() {
                    @Override
                    public void onCompleted(Exception e, File file) {
                        if (progressDialog.isShowing()) progressDialog.dismiss();

                        if (file != null) {
                            try {
                                finish();
                                overridePendingTransition(0, 0);

                                //Intent intent = new Intent(Intent.ACTION_VIEW);
                                //Uri uri = Uri.fromFile(new File(downloadedApk.getAbsolutePath()));
                                //intent.setDataAndType(uri, "application/vnd.android.package-archive");
                                //startActivity(Intent.createChooser(intent, "Installation de l'application DistriMobile"));

                                File fileApk = new File(downloadedApk.getAbsolutePath());
                                InstallFile(fileApk);

                            } catch (Exception ex) {
                                Log.e(getClass().getName(), "L'installation de la mise à jour a échoué", ex);
                                Toast.makeText(getApplicationContext(), "L'installation de la mise à jour a échoué", Toast.LENGTH_SHORT).show();

                                finish();
                                overridePendingTransition(0, 0);
                            }
                        } else {
                            popupMessageSimple("Veuillez rééssayer ...");
                        }
                    }
                });
    }

    private void telechargerApkBarcodeScanner() {
        final File downloadedApk = new File(Environment.getExternalStorageDirectory(), barcodescanner_apk_name);

        progressDialog.dismiss();

        progressDialog = new ProgressDialog(Activity_Lancement.this, R.style.ProgressBar);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Téléchargement de la mise à jour de Barcode Scanner ...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIndeterminate(false);
        progressDialog.setProgressNumberFormat(null);

        progressDialog.show();

        Ion.with(Activity_Lancement.this)
                .load(barcodescanner_url_version_apk)
                .progressDialog(progressDialog)
                .progress(new ProgressCallback() {
                    @Override
                    public void onProgress(long downloaded, long total) {
                        System.out.println("" + downloaded + " / " + total);
                    }
                })
                .write(downloadedApk)
                .setCallback(new FutureCallback<File>() {
                    @Override
                    public void onCompleted(Exception e, File file) {
                        if (progressDialog.isShowing()) progressDialog.dismiss();

                        if (file != null) {
                            try {
                                finish();
                                overridePendingTransition(0, 0);

//                                Intent intent = new Intent(Intent.ACTION_VIEW);
//                                Uri uri = Uri.fromFile(new File(downloadedApk.getAbsolutePath()));
//                                intent.setDataAndType(uri, "application/vnd.android.package-archive");
//                                startActivity(Intent.createChooser(intent, "Installation de l'application Barcode Scanner"));

                                File fileApk = new File(downloadedApk.getAbsolutePath());
                                InstallFile(fileApk);

                            } catch (Exception ex) {
                                Log.e(getClass().getName(), "L'installation de la mise à jour a échoué", ex);
                                Toast.makeText(getApplicationContext(), "L'installation de la mise à jour a échoué", Toast.LENGTH_SHORT).show();

                                finish();
                                overridePendingTransition(0, 0);
                            }
                        } else {
                            popupMessageSimple("Veuillez rééssayer ...");
                        }
                    }
                });
    }

    private void InstallFile(File prmFile) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", prmFile);
            Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
            openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            openFileIntent.setData(contentUri);
            startActivity(openFileIntent);
        } else {
            Uri uri = Uri.fromFile(prmFile);
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            install.setDataAndType(uri, "application/vnd.android.package-archive");
            startActivity(install);
        }
    }

    private void popupMessageSimple(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Lancement.this, R.style.ProgressBar);
        builder.setTitle("Une erreur est survenue !");
        builder.setCancelable(false);
        builder.setMessage(message)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();

                        finish();
                        overridePendingTransition(0, 0);
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUESTCODE_STORAGE_PERMISSION) {
            if (storagePermitted(Activity_Lancement.this)) {
                checkMAJAplusManager();
            }
        }
    }
}
