package com.sheep.gamegroup.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.util.DataKey;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.greenrobot.eventbus.EventBus;


/**
 * Created by Administrator on 2017/12/22.
 */

public class AppAddOrDelReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        String action = intent.getAction();
        if(action == null)
            return;
        switch (action){
            case Intent.ACTION_PACKAGE_REMOVED://卸载的监听
                String willInstallApkPackageName = DataUtil.getAsString(DataKey.KEY_WILL_INSTALL_APK_PACKAGE_NAME, null);
                if(!TextUtils.isEmpty(willInstallApkPackageName) && TextUtils.equals(getPackageName(intent), willInstallApkPackageName)){
                    String willInstallApkPath = DataUtil.getAsString(DataKey.KEY_WILL_INSTALL_APK_PATH, null);
                    if(!TextUtils.isEmpty(willInstallApkPath)){
                        //清除掉记录
                        DataUtil.putAsString(DataKey.KEY_WILL_INSTALL_APK_PATH, "");
                        DataUtil.putAsString(DataKey.KEY_WILL_INSTALL_APK_PACKAGE_NAME, "");
                        //重新安装
                        ApkUtils.installApk(SheepApp.getInstance(), willInstallApkPath);
                    }
                }
                break;
        }
        if(Intent.ACTION_PACKAGE_ADDED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_REPLACED.equals(action)){
            ApkUtils.getInstance().clear();
            EventBus.getDefault().post(intent);
        }

        /*
          安装失败
         */
        if(Intent.ACTION_INSTALL_FAILURE.equals(action)){
            try {
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        String cachePackageName = DataUtil.getAsString(DataKey.KEY_INSTALL_APK_PACKAGE_NAME, "");
                        if(TextUtils.equals(getPackageName(intent), cachePackageName)){
                            G.showToast("安装失败，请检查是否空间不足或其他问题!");
                        }
                    }
                }, 0);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    private String getPackageName(Intent intent) {
        String dataString = intent.getDataString();
        if(!TextUtils.isEmpty(dataString)){
            return dataString.replace("package:","");
        }
        return dataString;
    }

}
