package com.xypower.mpmaster;

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

public class UpdateReceiver extends BroadcastReceiver {

    private static final String TAG = UpdateReceiver.class.getSimpleName();

    private static final String APP_PACKAGE_MPAPP = "com.xypower.mpapp";

    @Override
    public void onReceive(Context context, Intent intent) {
        String packageName = intent.getDataString();

        packageChanged(context, intent.getAction(), packageName, APP_PACKAGE_MPAPP);
        packageChanged(context, intent.getAction(), packageName, context.getPackageName());
    }

    private void packageChanged(Context context, String action, String packageName, String targetPackageName) {
        if (action.equals(Intent.ACTION_PACKAGE_REPLACED)) { // Upgrade Broadcast
            Log.e(TAG, "onReceive:Upgraded and Restart the App:" + targetPackageName);
            MpMasterService.resetVersions();
            if (packageName.equals("package:" + targetPackageName)) {
                // SysApi.enableApp(context, targetPackageName);
                restartAPP(context, targetPackageName);
            }
        } else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {// Install broadcast
            Log.e(TAG, "onReceive:Installed and Start the App:" + targetPackageName);
            if (packageName.equals("package:" + targetPackageName)) {
                /*SystemUtil.reBootDevice();*/
                // SysApi.enableApp(context, targetPackageName);
                restartAPP(context, targetPackageName);
            }
        } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) { // Uninstall
            // Logger.e(TAG, "onReceive:uninstall" + packageName);
        }
    }

    public static void restartAPP(Context context, String packageName) {
        Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(packageName);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
        // ActManager.getAppManager().finishAllActivity();
    }
}