import { Plane, calculatePlaneIndices } from './Plane';
import { Texture } from '../texture';
import { CanvasRenderer } from '../renderers/CanvasRenderer';
import { Mesh } from './Mesh';

//提前计算好的索引
const indicesNN = calculatePlaneIndices(4, 4)
/**
 * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful
 * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically
 *
 *```js
 * let Plane9 = new NineSlicePlane(Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15);
 *  ```
 * <pre>
 *      A                          B
 *    +---+----------------------+---+
 *  C | 1 |          2           | 3 |
 *    +---+----------------------+---+
 *    |   |                      |   |
 *    | 4 |          5           | 6 |
 *    |   |                      |   |
 *    +---+----------------------+---+
 *  D | 7 |          8           | 9 |
 *    +---+----------------------+---+

 *  When changing this objects width and/or height:
 *     areas 1 3 7 and 9 will remain unscaled.
 *     areas 2 and 8 will be stretched horizontally
 *     areas 4 and 6 will be stretched vertically
 *     area 5 will be stretched both horizontally and vertically
 * </pre>
 *
 * @class
 * @extends Mesh 继承MESH
 *
 */
export class NineSlicePlane extends Mesh {
    /**
     * 原始宽度
     */
    private _origWidth: number;
    /**
     * 原始高度
     */
    private _origHeight: number;
    /**
     * 左边宽度
     */
    private _leftWidth: number;
    /**
     * 右边宽度
     */
    private _rightWidth: number;
    /**
     * 上边高度
     */
    private _topHeight: number;
    /**
     * 下边高度
     */
    private _bottomHeight: number;

    /**
     * @param {Texture} texture 纹理
     * @param {int} [leftWidth=10] size of the left vertical bar (A)
     * @param {int} [topHeight=10] size of the top horizontal bar (C)
     * @param {int} [rightWidth=10] size of the right vertical bar (B)
     * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D)
     */
    constructor(texture: Texture, leftWidth: number = 10, topHeight: number = 10, rightWidth: number = 10, bottomHeight: number = 10) {
        super(texture);
        //考虑对于未加载好的图片怎么处理吧，肯定需要加在onTextureUpdate的
        this._origWidth = texture.orig.width;
        this._origHeight = texture.orig.height;

        this._width = this._origWidth;

        this._height = this._origHeight;

        this._leftWidth = leftWidth;

        this._rightWidth = rightWidth;

        this._topHeight = topHeight;

        this._bottomHeight = bottomHeight;

        //计算索引，完全不用变，所以提前计算
        this._indices = indicesNN;
        //顶点数量长度可以确定先
        this._vertices = new Float32Array(4 * 4 * 2);
        //uv长度也可以确定先
        this._uvs = new Float32Array(4 * 4 * 2);

        this.refresh(true);
    }

    /**
     * 更新水平顶点
     */
    private updateHorizontalVertices() {
        const vertices = this._vertices;

        const h = this._topHeight + this._bottomHeight;
        const scale = this._height > h ? 1.0 : this._height / h;

        vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale;
        vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale);
        vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height;
    }

    /**
     * 更新垂直顶点
     */
    private updateVerticalVertices() {
        const vertices = this._vertices;

        const w = this._leftWidth + this._rightWidth;
        const scale = this._width > w ? 1.0 : this._width / w;

        vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale;
        vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale);
        vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width;
    }

    /**
     * canvas渲染
     * 考虑是否用缓存，不然每次相当于9次绘制，到时应该是集成到一个插件里的
     * @private
     * @param {CanvasRenderer} renderer
     */
    _renderCanvas(renderer: CanvasRenderer) {
        const context = renderer.context;
        context.globalAlpha = this._worldAlpha;
        renderer.setBlendMode(this.blendMode);
        const transform = this.worldMatrix;
        context.setTransform(
            transform.a,
            transform.b,
            transform.c,
            transform.d,
            transform.tx,
            transform.ty
        );
        const base = this.texture.baseTexture;
        const textureSource = base.source;
        const w = base.width;
        const h = base.height;

        this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11);
        this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13);
        this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15);
        this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19);
        this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21);
        this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23);
        this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27);
        this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29);
        this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31);
    }

    /**
     * 绘制某块平面
     * 至少1像素
     * @private
     * @param {CanvasRenderingContext2D} context - 上下文
     * @param {CanvasImageSource} textureSource - 图片标签
     * @param {number} w - 图片宽度
     * @param {number} h - 图片高度
     * @param {number} x1 - x index 1
     * @param {number} y1 - y index 1
     * @param {number} x2 - x index 2
     * @param {number} y2 - y index 2
     */
    private drawSegment(context, textureSource, w, h, x1, y1, x2, y2) {
        // otherwise you get weird results when using slices of that are 0 wide or high.
        const uvs = this._uvs;
        const vertices = this._vertices;

        let sw = (uvs[x2] - uvs[x1]) * w;
        let sh = (uvs[y2] - uvs[y1]) * h;
        let dw = vertices[x2] - vertices[x1];
        let dh = vertices[y2] - vertices[y1];

        // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn.
        if (sw < 1) {
            sw = 1;
        }

        if (sh < 1) {
            sh = 1;
        }

        // make sure destination is at least 1 pixel wide and high, otherwise you get
        // lines when rendering close to original size.
        if (dw < 1) {
            dw = 1;
        }

        if (dh < 1) {
            dh = 1;
        }

        context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh);
    }

    /**
     * 宽度
     * @member {number}
     */
    get width() {
        return this._width;
    }

    /**
     * 不再修改缩放，设置后会修改uv和顶点
     */
    set width(value) {
        this._width = value;
        this._needRefresh = true;
    }

    /**
     * 高度
     * @member {number}
     */
    get height() {
        return this._height;
    }
    /**
     * 不再修改缩放，设置后会修改uv和顶点
     */
    set height(value) {
        this._height = value;
        this._needRefresh = true;
    }

    /**
     * The width of the left column
     *
     * @member {number}
     */
    get leftWidth() {
        return this._leftWidth;
    }

    set leftWidth(value) {
        this._leftWidth = value;
        this._needRefresh = true;
    }

    /**
     * The width of the right column
     *
     * @member {number}
     */
    get rightWidth() {
        return this._rightWidth;
    }

    set rightWidth(value) {
        this._rightWidth = value;
        this._needRefresh = true;
    }

    /**
     * The height of the top row
     *
     * @member {number}
     */
    get topHeight() {
        return this._topHeight;
    }

    set topHeight(value) {
        this._topHeight = value;
        this._needRefresh = true;
    }

    /**
     * The height of the bottom row
     *
     * @member {number}
     */
    get bottomHeight() {
        return this._bottomHeight;
    }

    set bottomHeight(value) {
        this._bottomHeight = value;
        this._needRefresh = true;
    }

    /**
     * 刷新所有坐标
     */
    _refresh() {

        const uvs = this._uvs;
        const texture = this.texture;

        this._origWidth = texture.orig.width;
        this._origHeight = texture.orig.height;

        const _uvw = 1.0 / this._origWidth;
        const _uvh = 1.0 / this._origHeight;

        uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0;
        uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0;
        uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1;
        uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1;

        uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth;
        uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth);
        uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight;
        uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight);

        this.updateHorizontalVertices();
        this.updateVerticalVertices();

        this._vertexDirty++;

        this.multiplyUvs();
    }
}
