// @ts-ignore
import { TaskDriver, TimeoutScheduler } from '@comtstore/iterator-driver'

class Fiber {
    constructor(){
        this.priority = 1
        this.scheduler = new TimeoutScheduler()
        /**
         * @type {((task: any) => void)[]}
         */
        this.callbackList = []
        this.taskDriver = new TaskDriver([], this.scheduler, (/** @type {any} */ task) => {
            this.callbackList.forEach(cb => cb(task))
        }, {
            autoStart: true,
            autoOverwrite: true,
            reverse: true
        })
    }


    getPriority(){
        return this.priority ++
    }

    /**
     * 
     * @param {function(any):void} fn 
     */
    addCallback(fn){
        const index = this.callbackList.findIndex(cb => cb === fn)
        if(index === -1){
            this.callbackList.push(fn)
        }
    }

    /**
     * 
     * @param {function(any):void} fn 
     */
    clearCallback(fn){
        const index = this.callbackList.findIndex(cb => cb === fn)
        if(index > -1){
            this.callbackList.splice(index, 1)
        }
    }
}

const fiber = new Fiber()
fiber.taskDriver.start()

export {
    fiber
}