package cc.winboll.studio.libappbase;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import cc.winboll.studio.libappbase.R;

/**
 * @Author 豆包&ZhanGSKen<zhangsken@qq.com>
 * @CreateTime 2025-11-11 19:58:00
 * @EditTime 2025-11-11 20:15:32
 * @Describe 应用异常报告观察活动窗口类
 * 应用发生未捕获崩溃时，由 CrashHandler 启动此页面，展示崩溃日志详情，
 * 提供复制日志、重启应用操作入口，便于开发者定位问题及用户恢复应用；
 * 页面初始化异常时捕获错误并输出调试日志，提升崩溃页面自身稳定性。
 */
public final class GlobalCrashActivity extends Activity
implements MenuItem.OnMenuItemClickListener {

    /** 日志标签 */
    public static final String TAG = "GlobalCrashActivity";

    /** 菜单标识：复制崩溃日志 */
    private static final int MENU_ITEM_COPY = 0;
    /** 菜单标识：重启应用 */
    private static final int MENU_ITEM_RESTART = 1;

    /** 崩溃报告自定义视图 */
    private GlobalCrashReportView mCrashReportView;
    /** 崩溃日志文本 */
    private String mCrashLog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogUtils.d(TAG, "onCreate: 初始化崩溃展示页面");

		final Context appContext = getApplicationContext();
		GlobalAppCrashSafetyWire.getInstance()
			.postResumeCrashSafetyWireHandler(appContext);

		mCrashLog = getIntent().getStringExtra(CrashHandler.EXTRA_CRASH_LOG);
		setContentView(R.layout.activity_globalcrash);

		mCrashReportView = findViewById(R.id.activityglobalcrashGlobalCrashReportView1);
		if (mCrashReportView != null) {
			mCrashReportView.setReport(mCrashLog);
			setActionBar(mCrashReportView.getToolbar());
		}

		if (getActionBar() != null) {
			getActionBar().setTitle(CrashHandler.TITTLE);
			final String appName = GlobalApplication.getAppName(appContext);
			getActionBar().setSubtitle(appName);
		}
		LogUtils.d(TAG, "onCreate: 崩溃页面初始化完成");
    }

    @Override
    public void onBackPressed() {
        restartApp();
    }

    /**
     * 重启当前应用
     */
    private void restartApp() {
        LogUtils.d(TAG, "restartApp: 执行应用重启操作");
        final PackageManager packageManager = getPackageManager();
        final Intent launchIntent = packageManager.getLaunchIntentForPackage(getPackageName());

        if (launchIntent != null) {
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
								  | Intent.FLAG_ACTIVITY_CLEAR_TOP
								  | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(launchIntent);
        }

        finish();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        final int itemId = item.getItemId();
        switch (itemId) {
            case MENU_ITEM_COPY:
                copyCrashLogToClipboard();
                break;
            case MENU_ITEM_RESTART:
                GlobalAppCrashSafetyWire.getInstance().resumeToMaximumImmediately();
                restartApp();
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_ITEM_COPY, 0, "Copy")
			.setOnMenuItemClickListener(this)
			.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        menu.add(0, MENU_ITEM_RESTART, 0, "Restart")
			.setOnMenuItemClickListener(this)
			.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        if (mCrashReportView != null) {
            mCrashReportView.updateMenuStyle();
        }
        return true;
    }

    /**
     * 复制崩溃日志到系统剪贴板
     */
    private void copyCrashLogToClipboard() {
        LogUtils.d(TAG, "copyCrashLogToClipboard: 复制崩溃日志到剪贴板");
        final ClipboardManager clipboardManager = (ClipboardManager)
			getSystemService(Context.CLIPBOARD_SERVICE);
        final ClipData clipData = ClipData.newPlainText(getPackageName(), mCrashLog);
        clipboardManager.setPrimaryClip(clipData);
        Toast.makeText(getApplication(), "The text is copied.", Toast.LENGTH_SHORT).show();
    }
}

