const useWS = require("./utils/server")
const startClient = require('./client/start.js')
const {infoStack} = require('./utils/stack.js')

const {anasysArgument} = require('./utils/arguments.js')
const originLog = console.log
const process = require('node:process');

let server = null

function useClientConsole(options = {}){
    return new Promise((resolve)=>{

        // 开启前端
        startClient(originLog, options)
        useWS(originLog, (ws) => {
            originLog('🔵 node-conosle => node已配置同步输出至浏览器端')
            server = ws
            resolve()
        }, options)

        // 获取栈信息
        function getLogStack() {
            const stack = new Error().stack.replace('Error','Console')
            return stack
        }

        console.log = function () {
            try {
                // 原生console.log
                options.terminalPrint && originLog( ...arguments)
                // 记录log内容与堆栈,处理stack信息，过滤error字样，去除前两条栈信息
                let stack = getLogStack()
                stack = stack.split('\n').slice(3).join('\n')
                const message = {
                    ModeCode: 'console',
                    params:anasysArgument(arguments,originLog),
                    stack:infoStack(stack,originLog)
                }
                server && server.send(JSON.stringify(message))

            } catch(error) {
                originLog('转发console时发生错误', error)

            }
        }






        // // 未捕获的异常
        // process.on('uncaughtException', (error,origin) => {
        //     setTimeout(()=>{
        //     originLog('rejectionHandled',origin)

        //         // 处理error stack
        //         const stack = error.stack.split('\n').slice('1').join('\n')
        //         const data = error.stack.split('\n')[0]

        //         server.send(JSON.stringify({ ModeCode: 'error',  stack,data }))
        //     },0)


        // });




    })
}

function initConsole(main, options = {}){
    const mergedOptions = {
        serverWsPort: 8888,
        clientPort: 8848,
        terminalPrint: false,
        ...options
    }
    useClientConsole(mergedOptions).then(()=>{

        try{
            if(main && typeof main==='function'){
                main()
            }

        } catch(error){
            // 处理error stack
            const stack = error.stack.split('\n').slice('1').join('\n')
            const params = [error.stack.split('\n')[0]]

            const message ={
                ModeCode: 'error',
                params,
                stack:infoStack(stack,originLog)
            }
            server.send(JSON.stringify(message))
        }
    } )
}

module.exports = initConsole

