import {
    RandomInt
} from "../script/utils";

// 参考： https://forum.cocos.org/t/creator/38530/56

cc.Class({
    extends: cc.Component,

    properties: {

    },

    start() {
        this._textureIdMapDataContainer = {};

        const sprite = cc.find('Canvas/bg_biga');
        sprite.on(cc.Node.EventType.TOUCH_START, () => {
            sprite.color = cc.color(RandomInt(255), RandomInt(255), RandomInt(255));
        });
        sprite._hitTest = this._hitTest.bind(this);

        const sprite2 = cc.find('Canvas/bg_biga2');
        sprite2.on(cc.Node.EventType.TOUCH_START, () => {
            sprite2.color = cc.color(RandomInt(255), RandomInt(255), RandomInt(255));
        });
        sprite2._hitTest = this._hitTest.bind(this);
    },

    _hitTest(location, listener) {
        const sprite = listener.owner;

        let spriteFrame = sprite.getComponent(cc.Sprite).spriteFrame;
        if (spriteFrame == null) {
            return false;
        }
        let posInNode = sprite.convertToNodeSpaceAR(location);
        let rect = spriteFrame.getRect();
        let offset = spriteFrame.getOffset();
        if ((posInNode.x < offset.x - (rect.width * sprite.anchorX))
            || (posInNode.y < offset.y - (rect.height * sprite.anchorY))
            || (posInNode.x > (offset.x + (rect.width * (1 - sprite.anchorX))))
            || (posInNode.y > (offset.y + (rect.height * (1 - sprite.anchorY))))) {
            return false;
        }

        let posInRect = cc.v2(
            parseInt(posInNode.x - offset.x + (rect.width * sprite.anchorX)),
            parseInt(posInNode.y - offset.y + (rect.height * sprite.anchorY))
        );

        let tex = spriteFrame.getTexture();
        if (tex instanceof cc.RenderTexture) {
            throw "图片宽高都小于512的时候，图片资源的packable属性要设置为false。";
        }

        var scale = 8;
        var cvs = this._textureIdMapDataContainer[tex.getId()];
        if (!cvs) {
            cvs = document.createElement("canvas");
            var ctx = cvs.getContext('2d');
            cvs.width = tex.width;
            cvs.height = tex.height;
            ctx.drawImage(tex.getHtmlElementObj(), 0, 0, tex.width, tex.height, 0, 0, tex.width / scale, tex.height / scale);
            this._textureIdMapDataContainer[tex.getId()] = cvs;
        }

        let data;
        var ctx = cvs.getContext('2d');
        if (spriteFrame.isRotated()) {
            data = ctx.getImageData((rect.x + posInRect.y) / scale, (rect.y + posInRect.x) / scale, 1, 1).data;
        } else {
            data = ctx.getImageData((rect.x + posInRect.x) / scale, (rect.y + rect.height - posInRect.y) / scale, 1, 1).data;
        }

        if (data[3] > 0) {
            return true;
        } else {
            return false;
        }
    },
});
