package com.emato.ich.update;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.emato.ich.utils.Log;
import com.emato.ich.utils.LoggingUtils;
import com.emato.ich.utils.ToastUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

public class USBUpdateReceiver extends BroadcastReceiver {

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

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        Log.i(TAG, "U盘挂载成功。3秒后开始更新！");
        ToastUtils.make(context, "U盘挂载成功。3秒后开始更新！");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "action：" + action);
        if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
                || action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)
                || action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {

            // 更新操作
            Log.i(TAG, "开始通过U盘更新应用程序");

            File apkFile = PackageManagerCompat.getUpdateAPKFile(context);

            // 文件不存在直接退出
            if (null == apkFile) {
                Log.w(TAG, "U盘根目录下不存在升级所需APK！");
                ToastUtils.make(context, "U盘根目录下不存在升级所需APK！请检查APK存放目录！");
                return;
            }

            PackageManagerCompat.install(context, apkFile.getPath(), context.getPackageManager(), new InstallListener() {
                @Override
                public void onInstallException(Exception e) {
                    // 更新异常
                    Log.e(TAG, "安装失败! ", e);
                }

                @Override
                public void onInstallSuccess() {
                    // 更新成功
                    PackageManagerCompat.restartApp(context);
                    //
                }
            });
        } else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
            Log.i(TAG, "U盘已移除。。。");
            ToastUtils.make(context, "检测到U盘已移除");
        }

    }

}
