import BaseTexture from './BaseTexture';
import TextureUvs from './TextureUvs';
import { EventDispatcher } from '../events/EventDispatcher';
import { Event } from "../events/Event";
import { Rectangle, Point } from '../math';
import { TextureCache } from '../utils';
import { SCALE_MODES } from '../const';
import TextureMatrix from './TextureMatrix';

/**
 * 一张图片或图集的一部分，如果没有frame。默认整张图片
 *
 * eg
 * let texture = Texture.fromUrl('assets/image.png');
 * let sprite1 = new Sprite(texture);
 * let sprite2 = new Sprite(texture);
 * 
 * @class
 * @extends EventDispatcher
 */
export default class Texture extends EventDispatcher {
    /**
     * 标记texture没有frame
     * 表示不是从图集来的固定frame。需要根据BaseTexture的更新而改变frame
     */
    private noFrame: boolean;
    /**
     * BaseTexture，必有
     */
    baseTexture: BaseTexture;
    /**
     * 实际绘制矩形框，对于有trimmed的纹理很重要
     * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
     * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
     */
    _frame: Rectangle;
    /**
     * 如果矩形边缘有透明像素被裁减后的缩小的区域
     * This is the trimmed area of original texture, before it was put in atlas
     * Please call `updateUvs()` after you change coordinates of `trim` manually.
     */
    trim: Rectangle;
    /**
     * 贴图是否可用，true为可用
     */
    valid: boolean;

    /**
     * 对应贴图uv
     * The WebGL UV data cache.
     */
    _uvs: TextureUvs;
    /**
     * 原始尺寸，放入图集前
     * This is the area of original texture, before it was put in atlas
     */
    orig: Rectangle;

    /**
     * 贴图旋转及镜像
     */
    _rotate: number;
    /**
     * 贴图的锚点，默认0，0，左上角，范围0到1
     * 
     * @default {0,0}
     */
    defaultAnchor: Point;

    /**
     * 更新的id标志
     */
    _updateID: number;

    /**
     * 一般不用，需要时再说
     * Contains data for uvs. May contain clamp settings and some matrices.
     * Its a bit heavy, so by default that object is not created.
     * @member {TextureMatrix}
     * @default null
     */
    transform: TextureMatrix;

    /**
     * The ids under which this Texture has been added to the texture cache. This is
     * automatically set as long as Texture.addToCache is used, but may not be set if a
     * Texture is added directly to the TextureCache array.
     *
     * @member {string[]}
     */
    textureCacheIds: string[];

    /**
     * 空纹理
     */
    static EMPTY: Texture;
    /**
     * 白贴图
     */
    static WHITE: Texture;
    /**
     * @param {BaseTexture} baseTexture - The base texture source to create the texture from
     * @param {Rectangle} [frame] - The rectangle frame of the texture to show
     * @param {Rectangle} [orig] - The area of original texture
     * @param {Rectangle} [trim] - Trimmed rectangle of original texture
     * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link GroupD8}
     * @param {Point} [anchor] - Default anchor point used for sprite placement / rotation
     * 暂时不需要rotate
     */
    constructor(
        baseTexture: BaseTexture | Texture,
        frame?: Rectangle,
        orig?: Rectangle,
        trim?: Rectangle,
        rotate?: number,
        anchor?: Point
    ) {
        super();
        this._instanceType = "Texture";
        this.noFrame = false;
        if (!frame) {
            //标记没有固定的frame
            this.noFrame = true;
            //frame初始化个，对于sprite计算顶点从而计算bound，有1的虽然是空贴图但会占位1
            frame = new Rectangle(0, 0, 1, 1);
            //如果改为0，对于没加载好的图片时问题很大，设置Sprite宽高会出现scale无穷大
            // frame = new Rectangle(0, 0, 0, 0);
        }

        //如果传入的是Texture，取其base
        if (baseTexture instanceof Texture) baseTexture = baseTexture.baseTexture;

        this.baseTexture = baseTexture;

        this._frame = frame;

        this.trim = trim || null;

        this.valid = false;

        this._uvs = null;

        this.orig = orig || frame;// new Rectangle(0, 0, 1, 1);

        this._rotate = Number(rotate || 0);

        if (baseTexture.hasLoaded) {//对于canvas形式的判断hasLoaded有问题，导致不能监听update，到时改
            if (this.noFrame) {
                frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height);
                // if there is no frame we should monitor for any base texture changes..
                baseTexture.addEventListener('update', this.onBaseTextureUpdated, this);
            }
            this.frame = frame;
        }
        else {
            baseTexture.once('loaded', this.onBaseTextureLoaded, this);
        }

        this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0);

        this._updateID = 0;

        this.transform = null;

        this.textureCacheIds = [];
    }

    /**
     * 更新方法，直接调用base的，source尺寸有改变，或内容有改变，基本用于Shape和TextField
     * 在base更新时会触发自己的
     */
    update() {
        this.baseTexture.update();
    }


    // 下面Loaded和Updated两个监听函数基本用于两种情况，不会用于图集中的纹理(除非图集还没加载好)
    // 1、canvas作为贴图需要监听尺寸变化，Shape里以及TextField里
    // 2、单张图片（如网络图片临时加载）需要监听尺寸变化，比如奖品图片，尺寸不一且未知
    /**
     * 
     * @private
     * @param {BaseTexture} baseTexture - The base texture.
     */
    private onBaseTextureLoaded(e: Event/*,baseTexture: BaseTexture*/) {
        var baseTexture = e.target;
        this._updateID++;

        //执行这个函数意味着noFrame为true
        // TODO this code looks confusing.. boo to abusing getters and setters!
        if (this.noFrame) {
            this.frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height);
            //如果是没传过固定的frame就要监听了
            this.baseTexture.addEventListener('update', this.onBaseTextureUpdated, this);
        }
        else {
            this.frame = this._frame;
        }
        //加载成功的时候有必要触发update吗？
        this.dispatchEvent("update")


        //加一个，监听texture，在BaseTexture加载完成后执行
        // Texture.from("asd.png").once("loaded",()=>{
        //     考虑是否有必要传参数，
        //     回调
        // })
        this.dispatchEvent("loaded")
    }

    /**
     * 
     * @private
     * @param {BaseTexture} baseTexture - The base texture.
     */
    private onBaseTextureUpdated(e: Event/*,baseTexture*/) {
        var baseTexture = e.target;
        //标志纹理已更新
        this._updateID++;
        //只有尺寸需要
        this._frame.width = baseTexture.width;
        this._frame.height = baseTexture.height;
        this.orig.width = this._frame.width;
        this.orig.height = this._frame.height;
        this.valid = baseTexture.hasLoaded;
        this.dispatchEvent("update")
    }

    /**
     * 销毁
     */
    destroy() {
        if (this.baseTexture) {
            //考虑是否销毁baseTexture
            // if (destroyBase) {
            //     // delete the texture if it exists in the texture cache..
            //     // this only needs to be removed if the base texture is actually destroyed too..
            //     if (TextureCache[this.baseTexture.imageUrl]) {
            //         Texture.removeFromCache(this.baseTexture.imageUrl);
            //     }
            //     this.baseTexture.destroy();
            // }
            this.baseTexture.removeEventListener('update', this.onBaseTextureUpdated, this);
            this.baseTexture.removeEventListener('loaded', this.onBaseTextureLoaded, this);
            this.baseTexture = null;
        }
        this._frame = null;
        this._uvs = null;
        this.trim = null;
        this.orig = null;
        this.valid = false;
        Texture.removeFromCache(this);
        this.textureCacheIds = null;
    }

    /**
     * 克隆
     * @return {Texture} The new texture
     */
    clone(): Texture {
        return new Texture(
            this.baseTexture,
            this.frame,
            this.orig,
            this.trim,
            this.rotate,
            this.defaultAnchor
        );
    }

    /**
     * 
     * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture.
     */
    updateUvs() {
        if (!this._uvs) this._uvs = new TextureUvs();
        this._uvs.set(this._frame, this.baseTexture, this.rotate);
        this._updateID++;
    }

    /**
      * The frame specifies the region of the base texture that this texture uses.
      * Please call `updateUvs()` after you change coordinates of `frame` manually.
      *
      * @member {Rectangle}
      */
    get frame() {
        return this._frame;
    }

    set frame(frame) {
        this._frame = frame;

        this.noFrame = false;

        const { x, y, width, height } = frame;
        const xNotFit = x + width > this.baseTexture.width;
        const yNotFit = y + height > this.baseTexture.height;

        if (xNotFit || yNotFit) {
            const relationship = xNotFit && yNotFit ? 'and' : 'or';
            const errorX = `X: ${x} + ${width} = ${x + width} > ${this.baseTexture.width}`;
            const errorY = `Y: ${y} + ${height} = ${y + height} > ${this.baseTexture.height}`;

            throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: '
                + `${errorX} ${relationship} ${errorY}`);
        }

        //标记是否可用
        this.valid = width && height && this.baseTexture.source && this.baseTexture.hasLoaded;

        //如果无裁切透明像素，无旋转，orig和frame完全一致
        if (!this.trim && !this.rotate) this.orig = frame;

        //如果可用，更新uv
        if (this.valid) this.updateUvs();

    }
    /**
     * Indicates whether the texture is rotated inside the atlas
     * set to 2 to compensate for texture packer rotation
     * set to 6 to compensate for spine packer rotation
     * can be used to rotate or mirror sprites
     * See {@link GroupD8} for explanation
     *
     * @member {number}
     */
    get rotate(): number {
        return this._rotate;
    }

    set rotate(rotate: number) {
        if (this._rotate != rotate) {
            this._rotate = rotate;
            if (this.valid) this.updateUvs();
        }
    }

    /**
     * 宽高都是贴图真实的宽高，不管trim
     * The width of the Texture in pixels.
     *
     * @member {number}
     */
    get width() {
        return this.orig.width;
    }

    /**
     * The height of the Texture in pixels.
     *
     * @member {number}
     */
    get height() {
        return this.orig.height;
    }

    //辅助方法
    /**
     * 通过image标签创建纹理
     * 会缓存非base64的图片
     * @param image 
     */
    static fromImage(image: HTMLImageElement, scaleMode: number = SCALE_MODES.LINEAR) {
        var imageUrl = image.src;
        let texture: Texture = TextureCache[imageUrl];
        if (!texture) {
            texture = new Texture(BaseTexture.fromImage(image, scaleMode));
            if (imageUrl.indexOf('data:') !== 0) Texture.addToCache(texture, imageUrl);
        }
        return texture;
    }
    /**
     * 不缓存base64，如需要，手动Texture.addToCache(texture,name),
     * 自己输入名字，不用base字符串作为key
     * @static
     * @param {string} imageUrl - 图片路径
     * @param {boolean} [crossorigin] - 是否跨域
     * @param {number} [scaleMode=settings.SCALE_MODE] - See {@link SCALE_MODES} for possible values
     * @return {Texture} The newly created texture
     */
    static fromUrl(
        imageUrl: string,
        crossorigin: boolean = true,
        scaleMode: number = SCALE_MODES.LINEAR): Texture {
        let texture = TextureCache[imageUrl];
        if (!texture) {
            texture = new Texture(BaseTexture.fromUrl(imageUrl, crossorigin, scaleMode));
            if (imageUrl.indexOf('data:') !== 0) Texture.addToCache(texture, imageUrl);
        }
        return texture;
    }

    /**
     * TexturePacker图集中的名字
     * @static
     * @param {string} frameId - The frame Id of the texture in the cache
     * @return {Texture} The newly created texture
     */
    static fromFrame(frameId: string): Texture {
        const texture = TextureCache[frameId];
        if (!texture) {
            throw new Error(`The frameId "${frameId}" does not exist in the texture cache`);
        }
        return texture;
    }

    /**
     * Helper function that creates a new Texture based on the given canvas element.
     * 不会自动缓存，有需要自己addToCache
     * @static
     * @param {HTMLCanvasElement} canvas - The canvas element source of the texture
     * @param {number} [scaleMode=settings.SCALE_MODE] - See {@link SCALE_MODES} for possible values
     * @param {string} [origin='canvas'] - A string origin of who created the base texture
     * @return {Texture} The newly created texture
     */
    static fromCanvas(canvas: HTMLCanvasElement, scaleMode: number = SCALE_MODES.LINEAR, origin: string = 'canvas'): Texture {
        return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin));
    }

    /**
     * 缓存的key(路径或frame名字)、图片标签，canvas标签，BaseTexture，Texture
     * 除了imageUrl类型的，其他都不会缓存，因为没有key
     * @static
     * @param {string|HTMLImageElement|HTMLCanvasElement|BaseTexture|Texture}source - Source to create texture from
     * @return {Texture} The newly created texture
     */
    static from(source: any): Texture {
        // TODO auto detect cross origin..
        // TODO pass in scale mode?
        if (typeof source === 'string') {
            const texture = TextureCache[source];
            if (!texture) {
                return Texture.fromUrl(source);
            }
            return texture;
        }
        else if (source instanceof HTMLImageElement) {
            return Texture.fromImage(source)
        }
        else if (source instanceof HTMLCanvasElement) {
            return Texture.fromCanvas(source, SCALE_MODES.LINEAR, 'canvas');
        }
        else if (source instanceof BaseTexture) {
            return new Texture(source);
        }
        //如果source本身就是Texture
        return source;
    }

    /**
     * 加入全局缓存，TextureCache[name]调用
     * @static
     * @param {Texture} texture - The Texture to add to the cache.
     * @param {string} id - The id that the Texture will be stored against.
     */
    static addToCache(texture: Texture, id: string) {
        if (id) {
            if (texture.textureCacheIds.indexOf(id) === -1) {
                texture.textureCacheIds.push(id);
            }
            if (TextureCache[id]) {
                //覆盖
                console.warn(`Texture added to the cache with an id [${id}] that already had an entry`);
            }
            TextureCache[id] = texture;
        }
    }

    /**
     * 从全局缓存中移除
     * @static
     * @param {string|Texture} texture - id of a Texture to be removed, or a Texture instance itself
     * @return {Texture|null} The Texture that was removed
     */
    static removeFromCache(texture: any): Texture {
        if (typeof texture === 'string') {
            const textureFromCache = TextureCache[texture];

            if (textureFromCache) {
                const index = textureFromCache.textureCacheIds.indexOf(texture);

                if (index > -1) {
                    textureFromCache.textureCacheIds.splice(index, 1);
                }

                delete TextureCache[texture];

                return textureFromCache;
            }
        }
        else if (texture && texture.textureCacheIds) {
            for (let i = 0; i < texture.textureCacheIds.length; ++i) {
                // Check that texture matches the one being passed in before deleting it from the cache.
                if (TextureCache[texture.textureCacheIds[i]] === texture) {
                    delete TextureCache[texture.textureCacheIds[i]];
                }
            }

            texture.textureCacheIds.length = 0;

            return texture;
        }

        return null;
    }
}

/**
 * 16*16的空白canvas
 */
function createWhiteTexture() {
    const canvas = document.createElement('canvas');
    canvas.width = 16;
    canvas.height = 16;
    const context = canvas.getContext('2d');
    context.fillStyle = 'white';
    context.fillRect(0, 0, 16, 16);
    return new Texture(new BaseTexture(canvas));
}

//将事件置空
function removeAllHandlers(tex) {
    tex.destroy = function _emptyDestroy() { /* empty */ };
    tex.addEventListener = function _emptyOn() { /* empty */ };
    tex.once = function _emptyOnce() { /* empty */ };
    tex.dispatchEvent = function _emptyEmit() { /* empty */ };
}

/**
 * 空纹理，用于绑定webgl绑定空纹理
 * @static
 * @constant
 */
Texture.EMPTY = new Texture(new BaseTexture());
removeAllHandlers(Texture.EMPTY);
removeAllHandlers(Texture.EMPTY.baseTexture);

/**
 * 白色纹理，几何形状的纹理16*16
 * @static
 * @constant
 */
Texture.WHITE = createWhiteTexture();
removeAllHandlers(Texture.WHITE);
removeAllHandlers(Texture.WHITE.baseTexture);
