package com.xypower.mpmaster;

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

import com.xypower.common.MicroPhotoContext;

import java.io.File;

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(context);
            if (packageName.equals("package:" + targetPackageName)) {
                // SysApi.enableApp(context, targetPackageName);
                restartAPP(context, targetPackageName, "App Upgraded");
            }
        } else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {// Install broadcast
            Log.e(TAG, "onReceive:Installed and Start the App:" + targetPackageName);
            MpMasterService.resetVersions(context);
            if (packageName.equals("package:" + targetPackageName)) {
                /*SystemUtil.reBootDevice();*/
                // SysApi.enableApp(context, targetPackageName);
                restartAPP(context, targetPackageName, "App Installed");
            }
        } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) { // Uninstall
            // Logger.e(TAG, "onReceive:uninstall" + packageName);
        }
    }

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

    private void tryToRestartApp(final Context context, final String targetPackageName, String reason) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.equals(targetPackageName, APP_PACKAGE_MPAPP)) {
                    startMpApp(context, reason);
                } else {
                    restartAPP(context, targetPackageName, reason);
                }
            }
        }, 10000);
    }

    public static void restartAPP(Context context, String packageName, String reason) {
        Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(packageName);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (!TextUtils.isEmpty(reason)) {
            intent.putExtra("reason", reason);
        }
        context.startActivity(intent);
        // ActManager.getAppManager().finishAllActivity();
    }

    private void startMpApp(final Context context, String reason) {
        try {

            if (MicroPhotoContext.isAppAlive(context, MicroPhotoContext.PACKAGE_NAME_MPAPP)) {
                return;
            }

            String appPath = MicroPhotoContext.buildMpAppDir(context);
            long ts = System.currentTimeMillis();

            File mpappDb = new File(appPath + "data/App.db");
            long modifiedTimeOfDb = 0;
            if (mpappDb.exists()) {
                modifiedTimeOfDb = mpappDb.lastModified();
            }
            if ((ts - modifiedTimeOfDb) > 12 * 1000) {
                // greater than 12 seconds
                // logger.warning("Start MpAPP as it is NOT running");
                MicroPhotoContext.restartMpApp(context, reason);
            }
        } catch (Exception ex) {

        }
    }
}