import DealDataWorker from './dealData.worker?worker'
import DealMapWorker from './dealMap.worker?worker'
import DealTimeWorker from './dealTime.worker?worker'
import DealPathWorker from './dealPath.worker?worker'
import DealVehicleDiffWorker from './dealVehicleDiff.worker?worker'
import { useStateStore } from '@/store/StateStore'

export default class Worker {
    constructor(root) {
        this.workerMap = {
            vehicle: DealDataWorker,
            map: DealMapWorker,
            time: DealTimeWorker,
            path: DealPathWorker,
            vehicleDiff: DealVehicleDiffWorker
        }
        this.stateStore = useStateStore()
        // this.root = root
        this.worker = {}
        this.initWorker()
        this.startTimer()
    }

    initWorker() {
        Object.keys(this.workerMap).map(key => this.create(key))
    }

    create(key) {
        let worker = this.workerMap[key]

        this.worker[key] = new worker() 
    }

    startTimer() {
        const self = this
        const worker = this.worker.time
        worker.postMessage('start')

        worker.onmessage = ({data}) => {
            self.stateStore.setData('currentTime', data)
        }
    }

    destroyData() {
        Object.keys(this.worker).map(worker => this.worker[worker] && this.worker[worker].terminate())
    }
}