import { _decorator, Component, log, sys } from 'cc';
import { uploadError } from '../comm';

export class ErrorManager {
    private static _instance: ErrorManager = null;
    // 用于存储已上报的错误指纹
    private reportedErrors: Set<string> = new Set();

    public static get instance(): ErrorManager {
        if (!this._instance) {
            this._instance = new ErrorManager();
        }
        return this._instance;
    }

    private constructor() {
        this.initialize();
    }

    private initialize(): void {
        // 捕获全局错误
        window.onerror = (message, source, lineno, colno, error) => {
            let errorMsg = `error: ${message}\nfrom: ${source}\npos: ${lineno}:${colno}\nstack: ${error?.stack || 'no io message'}`;
            this.reportError(errorMsg);
            return true;
        };

        // 捕获未处理的Promise错误
        window.onunhandledrejection = (event) => {
            let errorMsg = `unhandledrejection: ${event.reason?.message || event.reason || 'unknown reason'}\nstack: ${event.reason?.stack || 'no stack info'}`;
            this.reportError(errorMsg);
        };
    }

    // 简单的指纹生成方法
    private generateErrorFingerprint(error: string): string {
        // 只取错误消息的前100个字符作为指纹
        return error.substring(0, 100);
    }

    // 手动上报错误
    public reportError(errorMessage: string): void {
        try {
            let fingerprint = this.generateErrorFingerprint(errorMessage);
            log("start report error", fingerprint);
            // 检查是否已经上报过相同错误
            if (this.reportedErrors.has(fingerprint)) {
                log("same error already reported, skip");
                return;
            }
            // 记录已上报错误
            this.reportedErrors.add(fingerprint);

            uploadError(errorMessage)
        } catch (err) {
            log("report error error", err);
        }
    }

}

// 初始化全局错误管理器
export function initErrorManager() {
    let errorManager = ErrorManager.instance;
    return errorManager;
}