type RGBA = Record<'r' | 'g' | 'b' | 'a', number>;



function imageChange(img: HTMLImageElement, colorize: (pixel: RGBA) => RGBA) {
    if (img.getAttribute('data-colorized'))
        return;
    img.crossOrigin = 'anonymous'
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    if (!ctx) return
    ctx.drawImage(img, 0, 0);
    var imgd = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var pix = imgd.data;
    for (var i = 0, n = pix.length; i < n; i += 4) {

        var pixel = colorize({ r: pix[i], g: pix[i + 1], b: pix[i + 2], a: pix[i + 3] });
        if (!!!pixel || pixel !== Object(pixel) || Object.prototype.toString.call(pixel) === '[object Array]') {

            if (i === 0) {
                throw 'The colorize option should return an object with at least one of "r", "g", "b", or "a" properties.';
            }

        } else {
            if (pixel.hasOwnProperty('r') && typeof pixel.r === 'number') {
                pix[i] = pixel.r;
            }
            if (pixel.hasOwnProperty('g')) {
                pix[i + 1] = pixel.g;
            }
            if (pixel.hasOwnProperty('b')) {
                pix[i + 2] = pixel.b;
            }
            if (pixel.hasOwnProperty('a')) {
                pix[i + 3] = pixel.a;
            }
        }

    }

    ctx.putImageData(imgd, 0, 0);
    img.setAttribute('data-colorized', 'true');
    img.src = canvas.toDataURL();
    return imgd;
}


/**
 * 
 * @param img 图片
 * @param colorize 图片rgb颜色修改
 * @example  
 * const colorize = useRgb()
 * layer.on('tileload', (e) => {
 *      colorize(e.tile, (pixel) => {
 *          pixel.g += 17;
 *          pixel.b += 90;
 *          return pixel;
 *      })
 *  }) 
 * @returns 
 */
function useRgb() {
    return imageChange;
}

export default useRgb