package it.integry.integrywmsnative.core.update;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import androidx.appcompat.app.AppCompatActivity;

import com.github.javiersantos.appupdater.AppUpdater;
import com.github.javiersantos.appupdater.enums.Display;
import com.github.javiersantos.appupdater.enums.UpdateFrom;

import java.io.File;

import javax.inject.Singleton;

import it.integry.integrywmsnative.core.class_router.BaseCustomConfiguration;
import it.integry.integrywmsnative.core.class_router.ClassRouter;
import it.integry.integrywmsnative.core.class_router.interfaces.ICustomConfiguration;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.utility.FileDownloader;
import it.integry.integrywmsnative.view.dialogs.DialogProgressView;

@Singleton
public class UpdatesManager {

    private AppCompatActivity mContext;

    public void init(AppCompatActivity activityContext) {
        this.mContext = activityContext;

        String suffix;
        ICustomConfiguration customConfiguration = ClassRouter.getInstance(ClassRouter.PATH.CUSTOM_CONFIGURATION);
        try {
            suffix = customConfiguration.getConfig(BaseCustomConfiguration.Keys.CUSTOM_DYNAMIC_VERSION_PATH);
            if (suffix == null) {
                suffix = "";
            }
        } catch (Exception e) {
            suffix = "";
        }

        String currentVersionUrl = "http://" + SettingsManager.i().getServer().getHost() + ":" + SettingsManager.i().getServer().getPort() + "/ems-api/wms/currentVersion";
        String currentDownloadUrl = "http://" + SettingsManager.i().getServer().getHost() + ":" + SettingsManager.i().getServer().getPort() + "/ems-api/wms/android-release" + suffix + ".apk";


        AppUpdater appUpdater = new AppUpdater(mContext)
                .setDisplay(Display.DIALOG)
                .setUpdateFrom(UpdateFrom.JSON)
                .setUpdateJSON(currentVersionUrl)
                .setButtonDoNotShowAgain(null)
                .setButtonUpdateClickListener((dialog, which) -> {
                    installAPK(currentDownloadUrl);
                });
        appUpdater.start();
    }


    private void installAPK(String downloadURL) {

        String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";

        var progressDialogBuilder = new DialogProgressView("Download", null, false);
        progressDialogBuilder.show(mContext.getSupportFragmentManager(), "tag");


        var fileDownloader = new FileDownloader()
                .setDestFolder(destination)
                .setUrlString(downloadURL)
                .setOnProgressUpdate(progress -> {
                    mContext.runOnUiThread(() -> {
                        progressDialogBuilder.setProgress(progress);
                    });
                })
                .setOnDownloadCompleted(destPath -> {

                    mContext.runOnUiThread(() -> {
                        progressDialogBuilder.dismiss();

                        Uri fileLoc;
                        Intent intent;

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

                        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);

                        mContext.startActivity(intent);
                    });

                });


        new Thread(() -> {
            try {
                fileDownloader.download();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
