package it.integry.integrywmsnative.core.update;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import com.github.javiersantos.appupdater.AppUpdater;
import com.github.javiersantos.appupdater.AppUpdaterUtils;
import com.github.javiersantos.appupdater.enums.AppUpdaterError;
import com.github.javiersantos.appupdater.enums.Display;
import com.github.javiersantos.appupdater.enums.UpdateFrom;
import com.github.javiersantos.appupdater.objects.Update;

import java.io.File;

import androidx.core.content.FileProvider;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.settings.SettingsManager;

public class UpdatesManager {

    public static void init(Activity context) {
        String currentVersionUrl = "http://" + SettingsManager.i().server.host + ":" + SettingsManager.i().server.port + "/ems-api/wms/currentVersion";
        String currentDownloadUrl = "http://" + SettingsManager.i().server.host + ":" + SettingsManager.i().server.port + "/ems-api/wms/android-release_v2.apk";


        AppUpdater appUpdater = new AppUpdater(context)
                .setDisplay(Display.DIALOG)
                .setUpdateFrom(UpdateFrom.JSON)
                .setUpdateJSON(currentVersionUrl)
                .setButtonUpdateClickListener((dialog, which) -> {

                    installAPK(context, currentDownloadUrl);
                });
        appUpdater.start();
    }


    private static void installAPK(Activity context, String downloadURL) {
        String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        String fileName = context.getResources().getString(R.string.app_name) + ".apk";
        destination += fileName;
        final Uri uri = Uri.parse("file://" + destination);

        //Delete update file if exists
        final File file = new File(destination);
        if (file.exists())
            file.delete();

        //set downloadmanager
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadURL));
        request.setDescription(context.getString(R.string.notification_update_download));
        request.setTitle(context.getString(R.string.app_name));

        //set destination
        request.setDestinationUri(uri);

        // get download service and enqueue file
        final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);

        //set BroadcastReceiver to install app when .apk is downloaded
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            public void onReceive(Context ctxt, Intent i) {

                Uri fileLoc;
                Intent intent;

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                    fileLoc = GenericFileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".core.update.GenericFileProvider", file);
                } else {
                    intent = new Intent(Intent.ACTION_VIEW);
                    fileLoc = Uri.fromFile(file);
                }

                intent.setDataAndType(fileLoc, "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                context.startActivity(intent);
            }
        };

        //register receiver for when .apk download is compete
        context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
}
