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.fromImage('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初始化个
            frame = new Rectangle(0, 0, 1, 1);
        }

        //如果传入的是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 || (baseTexture.source && baseTexture.source.getContext)) {//对于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;
    }

    //辅助方法
    /**
     * 会缓存
     * @param {string} url 
     */
    static fromUrl(url: string) {
        let texture = TextureCache[url];
        if (!texture) {
            texture = new Texture(BaseTexture.fromUrl(url));
            Texture.addToCache(texture, url);
        }
        return texture;
    }

    static fromCanvas(canvas: HTMLCanvasElement, origin: string = 'canvas') {
        return new Texture(BaseTexture.fromCanvas(canvas, origin))
    }

    static fromData(data) {
        return new Texture(BaseTexture.fromData(data))
    }

    static fromImage(image: HTMLImageElement) {
        var imageUrl = image.src;
        let texture: Texture = TextureCache[imageUrl];
        if (!texture) {
            texture = new Texture(BaseTexture.fromImage(image));
            if (imageUrl && imageUrl.indexOf('data:') !== 0) Texture.addToCache(texture, imageUrl);
        }
        return texture;
    }
    //不包括data形式
    static from(anything: string | HTMLCanvasElement | HTMLImageElement) {
        //路径
        if (typeof anything === 'string') {
            return Texture.fromUrl(anything);
        }
        //@ts-ignore
        else if (anything.data) {
            return Texture.fromData(anything);
        }
        //@ts-ignore canvas
        else if (anything.getContext) {
            //@ts-ignore
            return Texture.fromCanvas(anything);
        } else {
            //@ts-ignore
            return Texture.fromImage(anything);
        }
    }

    /**
     * 加入全局缓存，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;
    }
}

//将事件置空
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的数据
 */
const whiteSource = {
    data: (function () {
        var arr = []
        for (var i = 0; i < 16 * 16 * 4; i++) {
            arr.push(255);
        }
        return new Uint8Array(arr)
    })(),
    width: 16,
    height: 16,
    type: null,
    path: null
}

/**
 * 白色纹理，几何形状的纹理16*16
 * 仅用于webgl模式的Graphics
 * @static
 * @constant
 */
Texture.WHITE = new Texture(new BaseTexture(whiteSource));
removeAllHandlers(Texture.WHITE);
removeAllHandlers(Texture.WHITE.baseTexture);
