"use strict";

class SpriteManager {
    _sprites = {};
    _gl;

    constructor (webGLRenderingContext) {
        this._gl = webGLRenderingContext;
    }    

    load(name, path) {
        var me = this;
        return new Promise((resolve) => {
            var image = new Image();
            image.onload = () => 
            {
                const gl = this._gl;
                const texture = gl.createTexture();
                gl.bindTexture(gl.TEXTURE_2D, texture);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
            
                if (false && this._isPowerOf2(image.width) && this._isPowerOf2(image.height)) {
                   gl.generateMipmap(gl.TEXTURE_2D);
                } else {
                   gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                   gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                   gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR )
                   gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR )
                }

                var sprite = new Sprite();
                sprite.width = image.width;
                sprite.height = image.height;
                sprite.texture = texture;
                this._sprites[name] = sprite;
                resolve();
            } 
            const cacheBuster = (new Date()).getTime();
            image.src = path + '?' + cacheBuster;
        });
    }

    get(name) {
        return this._sprites[name];
    }

    _isPowerOf2(value) {
        return (value & (value - 1)) == 0;
      }
}