//svetofor 
const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))

async function trafficLight(element, timeGreen, timeYellow, timeRed){
    while (true){
        element.style.backgroundColor = 'green'
        await delay(timeGreen)
        element.style.backgroundColor = 'yellow'
        await delay(timeYellow)
        element.style.backgroundColor = 'red'
        await delay(timeRed)
    }
}

//domEventPromise
function domEventPromise(element, eventName) {
    return new Promise((resolve) => {
        element.addEventListener(eventName, function toDelete (e) {
            element.removeEventListener(eventName, toDelete)
            resolve(e)
        })
    })
}

//PedestrianTrafficLight
function changeColor(element, color) {
    element.style.backgroundColor = color
}

async function pedestrianTrafficLight(element, element2, timeGreen, timeYellow, timeRed) {
    while(true) {
        delay(timeGreen / 3).then(() => btn.disabled = false)
        changeColor(element, 'green')
        changeColor(element2, 'red')
        await Promise.race([delay(timeGreen), domEventPromise(btn, 'click')])

        btn.disabled = true
        changeColor(element, 'yellow')
        await delay(timeYellow)

        changeColor(element, 'red')
        changeColor(element2, 'green')
        await delay(timeRed)

        changeColor(element, 'yellow')
        changeColor(element2, 'red')
        await delay(timeYellow)
    }
}

pedestrianTrafficLight(trafficLightContainer, pedestrianTrafficLightContainer, 10000, 3000, 15000)

//speedtest
async function speedtest(getPromise, count, parallel=1){
    let startTime = performance.now()
    
    for (let i = 0; i < count; i++) {
        let promises = []
        for (let j = 0; j < parallel; j++) {
            promises.push(getPromise())
        }
        await Promise.all(promises)
    }

    let duration = performance.now() - startTime
    let querySpeed = count / duration
    let queryDuration = duration / count
    let parallelSpeed = (count * parallel) / duration
    let parallelDuration = duration / (count * parallel)

        return {
            duration,
            querySpeed,
            queryDuration, 
            parallelSpeed,
            parallelDuration
        }
    }

speedtest(() => delay(1000), 10, 10 ).then(result => console.log(result))
speedtest(() => fetch('http://swapi.dev/api/people/1').then(res => res.json()), 3, 1).then(result => console.log(result))