package com.emato.ich.update;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;

import com.emato.ich.utils.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.emato.ich.MainActivity;
import com.emato.ich.utils.LoggingUtils;
import com.emato.ich.utils.StringUtils;
import com.emato.ich.utils.ToastUtils;
import com.xuexiang.xupdate.entity.DownloadEntity;
import com.xuexiang.xupdate.listener.OnInstallListener;

import org.jetbrains.annotations.NotNull;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 自定义的安装类
 */
public class PackageManagerCompat implements OnInstallListener {

    private static final String TAG = PackageManagerCompat.class.getName();

    /*public static void install(Activity activity, File apkFile, OnInstallListener listener){
        try{
            Intent intent =new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //Uri uri = Uri.fromFile(apkFile);
            Uri uri = null;
            //todo N FileProvider
            //todo O install permission
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                uri = androidx.core.content.FileProvider.getUriForFile(activity,activity.getPackageName()+".fileprovider", apkFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }else{
                uri = Uri.fromFile(apkFile);
            }
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            activity.startActivity(intent);
            listener.onInstallSuccess();
        } catch (Exception e) {
            listener.onInstallException(e);
        }
    }*/

    /**
     * android 9.0获取外置sdcard和U盘路径，并区分
     * @param mContext  上下文
     *  SD = "内部存储"; EXT = "SD卡"; USB = "U盘"
     * @return apk
     */
    public static File getUpdateAPKFile(Context mContext){
        String targetpath = "";
        String keyword = "USB";

        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);

        Class<?> storageVolumeClazz = null;
        File file = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");

            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");

            Method getPath = storageVolumeClazz.getMethod("getPath");

            Object result = getVolumeList.invoke(mStorageManager);

            final int length = Array.getLength(result);

            Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel");

            for (int i = 0; i < length; i++){
                StorageVolume storageVolumeElement = (StorageVolume) Array.get(result, i);
                String userLabel = (String) getUserLabel.invoke(storageVolumeElement);
                String path = (String) getPath.invoke(storageVolumeElement);

                if(!userLabel.contains("内部存储") && !storageVolumeElement.isEmulated()){
                    targetpath = path;
                    targetpath = targetpath +"/com.emato.ich.apk";
                    file = new File(targetpath);
                    if (!file.exists()) {
                        ToastUtils.make(mContext, "U盘根目录下不存在升级所需APK！请检查APK存放目录！");
                        return file;
                    }
                }
            }
        } catch (ClassNotFoundException e){
            Log.e(TAG, "类找不到异常", e);
            LoggingUtils.sendAppErrorLog("类找不到异常", e);
        } catch (InvocationTargetException e) {
            Log.e(TAG, "反射调用目标方法异常", e);
            LoggingUtils.sendAppErrorLog("反射调用目标方法异常", e);
        } catch (NoSuchMethodException e) {
            Log.e(TAG, "反射找不到目标方法", e);
            LoggingUtils.sendAppErrorLog("反射找不到目标方法", e);
        } catch (IllegalAccessException e) {
            Log.e(TAG, "没有权限", e);
            LoggingUtils.sendAppErrorLog("没有权限", e);
        }
        return file;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void install(Context context, String apkFilePath, PackageManager packageManager, InstallListener listener) {
        try {
            Log.i(TAG, "install: 应用程序开始安装! " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            File apkFile = new File(apkFilePath);
            if (!apkFile.exists()) {
                throw new RuntimeException("文件不存在! 更新失败! ");
            }
            PackageInstaller packageInstaller = packageManager.getPackageInstaller();
            PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
            sessionParams.setSize(apkFile.length());

            int sessionId = createSession(packageInstaller, sessionParams);
            if (sessionId != -1) {
                boolean copySuccess = copyInstallFile(packageInstaller, sessionId, apkFilePath, listener);
                if (copySuccess) {
                    execInstallCommand(context, packageInstaller, sessionId, listener);
                }
            }
            Log.i(TAG, "install: 应用程序安装完成! " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (Exception e) {
            Log.i(TAG, "安装异常！",e);
            listener.onInstallException(e);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static int createSession(PackageInstaller packageInstaller,
                                     PackageInstaller.SessionParams sessionParams) {
        int sessionId = -1;
        try {
            sessionId = packageInstaller.createSession(sessionParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionId;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static boolean copyInstallFile(PackageInstaller packageInstaller,
                                           int sessionId, String apkFilePath, InstallListener listener) {
        InputStream in = null;
        OutputStream out = null;
        PackageInstaller.Session session = null;
        boolean success = false;
        try {
            File apkFile = new File(apkFilePath);
            session = packageInstaller.openSession(sessionId);
            out = session.openWrite("base.apk", 0, apkFile.length());
            in = new FileInputStream(apkFile);
            int total = 0, c;
            byte[] buffer = new byte[65536];
            while ((c = in.read(buffer)) != -1) {
                total += c;
                out.write(buffer, 0, c);
            }
            session.fsync(out);
            success = true;
        } catch (IOException e) {
            listener.onInstallException(e);
        } finally {
            closeQuietly(out, listener);
            closeQuietly(in, listener);
            closeQuietly(session, listener);
        }
        return success;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static void execInstallCommand(Context context, PackageInstaller packageInstaller, int sessionId, InstallListener listener) {
        PackageInstaller.Session session = null;
        try {
            session = packageInstaller.openSession(sessionId);
            Intent intent = new Intent(context, InstallResultReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            session.commit(pendingIntent.getIntentSender());
            listener.onInstallSuccess();
        } catch (IOException e) {
            listener.onInstallException(e);
        } finally {
            closeQuietly(session, listener);
        }
    }
    private static void closeQuietly(Closeable c, InstallListener listener) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException ignored) {
                listener.onInstallException(ignored);
            }
        }
    }
    /**
     * 重启
     * @param context   应用上下文
     */
    public static void restartApp(Context context) {
        Log.i(TAG, "restartApp: 应用程序重启中! 日期=====>" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
            if (intent != null && !StringUtils.isNullOrEmpty(intent.getAction()) && intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
                Intent intent1 = new Intent(context, MainActivity.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent1);
                Log.i(TAG, "restartApp: ======================================>重启成功");
            }
        } catch (Exception e) {
            Log.e(TAG, "restartApp: ======================================>重启失败! ", e);
            LoggingUtils.sendErrorLog("业务异常: ======================================>重启失败! ", e);
        }
//        PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);


//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0及以上
//            mgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, restartIntent);
//
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4及以上
//            mgr.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, restartIntent);
//        }
        Log.i(TAG, "restartApp: 应用程序重启完成! 日期=====>" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    @Override
    public boolean onInstallApk(@NonNull @NotNull Context context, @NonNull @NotNull File apkFile, @NonNull @NotNull DownloadEntity downloadEntity) {
        AtomicBoolean flag = new AtomicBoolean(true);
        install(context, apkFile.getAbsolutePath(), context.getPackageManager(), new InstallListener(){

            @Override
            public void onInstallException(Exception e) {
                Log.e(TAG, "onInstallException: 安装失败! ", e);
                flag.set(false);
            }

            @Override
            public void onInstallSuccess() {
                restartApp(context);
            }
        });
        return flag.get();
    }

    @Override
    public void onInstallApkSuccess() {
        Log.i(TAG, "onInstallApkSuccess: 安装成功! ");
    }
}
