/* global Image */

const newResourceItem = (resources, name, data) => {
    return new Promise((resolve, reject) => {
        const newImage = new Image()
        newImage.onload = () => {
            resources[name] = {
                type: 'image',
                data: newImage
            }
            resolve(resources[name])
        }
        newImage.onerror = reject

        newImage.src = data
    })
}

const cutImage = (img, { x, y, w, h }) => {
    const canvas = document.createElement('canvas')
    let ctx = canvas.getContext('2d')

    canvas.width = w
    canvas.height = h
    ctx.clearRect(0, 0, w, h)
    ctx.drawImage(img, x, y, w, h, 0, 0, w, h)

    const data = canvas.toDataURL('image/png')

    ctx = null
    canvas.remove()

    return data
}

const loadAtlas = (path, data, resources) => {
    return new Promise((resolve, reject) => {
        const img = new Image()

        img.onload = () => {
            const promises = data.map(item => {
                const imgcut = cutImage(img, item)
                return newResourceItem(resources, item.name, imgcut)
            })

            const result = Promise.all(promises)
            resolve(result)
        }

        img.onerror = reject

        img.src = path
    })
}

export default loadAtlas
