
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
/*-------------------------------------------------------------------------------------------*/
if(typeof $Global == 'undefined')
{
    require(process.cwd()+'/nodejs/config/config.cnf.js') 
}

var 
{
    Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

// worker初始操作
/*-------------------------------------------------------------------------------------------*/	
class worker
{
    static init() 
    {
        function pool(index)
        {
            let worker = new Worker
            (
                __filename, 
                {
                    workerData: {}
                }
            );
            worker.on
            (
                'message', data=>
                {
                    try 
                    {
                        if($ExtendPool.worker.data[data.$unique])
                        {
                            if(data.error)
                            {
                                console.error(`THREAD发生错误:${data.error}`);
                                $ExtendPool.worker.data[data.$unique].rej(data.result);
                            }
                            else
                            {
                                $ExtendPool.worker.data[data.$unique].res(data.result);
                            }
                        }
                    } 
                    catch (error) 
                    {
                        console.error('[THREAD]解析错误',error)
                    }
                }
            );
            worker.on
            (
                'error', error=>
                {
                    console.error(`THREAD发生错误[未捕捉]`,error);
                }
            ); 
            worker.on
            (
                'exit', () => 
                {
                    console.info(`THREAD关闭，即将新开线程`,worker.threadId);
                    $ExtendPool.worker.pool.map[index]=null
                }
            );
            return worker;
        }

        console.info(`THREAD初始化中: 请等待...`); 
        let poolw=$Sys.model('/fun/pool')
        $ExtendPool.worker.pool=new poolw($ExtendPool.worker.count,pool,result=>result)
        console.info(`THREAD初始化完成: 总共${$ExtendPool.worker.count}个线程`);     
    }

    static parse(data,timeout=5000,count)
    {
        let uni=Math.random().toString();
        $ExtendPool.worker.pool.hash(count).postMessage({$unique:uni,data:data});
        let pro= new Promise
        (
            function(reslove,rej)
            {
                $ExtendPool.worker.data[uni]={time:Date.now,rej:rej,res:reslove}
            }
        )
        return $Sys.race(pro,timeout,'THREAD').finally
        (
            ()=>
            {
                Reflect.deleteProperty($ExtendPool.worker.data,uni)
            }
        )
    }

    static share(path,data)
    {
        for (let index = 0; index < $ExtendPool.worker.pool.map.length; index++) 
        {
            if($ExtendPool.worker.pool.map[index] && $ExtendPool.worker.pool.map[index].con)
            {
                $ExtendPool.worker.pool.map[index].con.postMessage({path:path,data:data,type:'share'})
            }
        }
    }

}
/*-------------------------------------------------------------------------------------------*/ 
! async function()
{
    if(typeof isMainThread == 'undefined')return false;
    if (isMainThread) 
    {
        module.exports=worker;
    }
    else
    {
        parentPort.on
        (
            'message',
            async function(workerData)
            {
                try 
                {
                    if(workerData.type=='share')
                    {
                        global[workerData.path]=workerData.data
                    }
                    else if(workerData.data.path)
                    {
                        let result
                        if(workerData.data.type=='view')
                        {
                            result=await $Sys.view(workerData.data.path,...workerData.data.data)
                        }
                        else if(workerData.data.type=='service')
                        {
                            result=await $Sys.service(workerData.data.path,workerData.data.method,[...workerData.data.data])
                        }
                        else
                        {
                            result=await $Sys.model(workerData.data.path,workerData.data.method,[...workerData.data.data])
                        }
                        parentPort.postMessage({$unique:workerData.$unique,result:result});
                    }
                    else
                    {
                        parentPort.postMessage({$unique:workerData.$unique,result:''});
                    }
                } 
                catch (error) 
                {
                    parentPort.postMessage({$unique:workerData.$unique,result:'',error:error.stack});
                }
            }
        )
    }      
}()