'use strict'

const colourTextures = {
    default: {
        width: 2,
        height: 2,
        data: new Float32Array([1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1])
    }
}

const failedColourTextureLookups = []

function getColourTexture (textureName) {
    const texture = colourTextures[textureName]
    if (texture) {
        return texture
    } else {
        if (!failedColourTextureLookups.includes(textureName)) {
            console.error(`getColourTexture failed to find texture '${textureName}'`)
            failedColourTextureLookups.push(textureName)
        }
        return colourTextures['default']
    }
}


const models = {
    default: {
        verts: [
            [-1,-1,-1], [-1,+1,-1], [+1,+1,-1], [+1,-1,-1],
            [-1,-1,+1], [-1,+1,+1], [+1,+1,+1], [+1,-1,+1],
        ],
        objects: [
            {
                name: 'bob',
                subObjects: [
                    {
                        brightness: 1.0,
                        lines: [],
                        tris: [],
                        quads: [
                            [0,1,2,3], [7,6,5,4],
                            [4,5,1,0], [6,7,3,2],
                            [0,3,7,4], [5,6,2,1],
                        ],
                    }
                ]
            }
        ]
    }
}

const failedModelLookups = []

function getModel (modelName) {
    const model = models[modelName]
    if (model) {
        return model
    } else {
        if (!failedModelLookups.includes(modelName)) {
            console.error(`getModel failed to find model '${modelName}'`)
            failedModelLookups.push(modelName)
        }
        return models['default']
    }
}



let colourTextureLoads = Object.keys(assets).length
function colourTextureLoaded () {
    if (--colourTextureLoads === 0) {
        window.requestAnimationFrame(() => {
            loaded()
        })
    }
}

Object.keys(assets).forEach(assetName => {
    const asset = assets[assetName]
    const assetType = asset.type
    const assetData = asset.data

    if (assetType === 'png') {
        const img = new Image()
        img.onload = () => {
            const width = img.width
            const height = img.height
            const canvas  = document.createElement('canvas')
            canvas.width = width
            canvas.height = height
            
            const ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0)
            const id = ctx.getImageData(0, 0, width, height).data
            colourTextures[assetName] = {
                width,
                height,
                data: new Float32Array(id)
            }
            colourTextureLoaded()
        }
        img.src = `data:image/png;base64,${assetData}`
    } else if (assetType === 'obj') {
        models[assetName] = assetData
        colourTextureLoaded()
    }
})