import AppFacade from "../Core/AppFacade";
import { ResConst } from "../Core/ConstDefine/ResConst";
import { ViewConst } from "../Core/ConstDefine/ViewConst";
import Controller from "../Core/Controller";
import SoundMgr from "../Core/Manager/SoundMgr";
import GameUtil from "../Core/Util/GameUtil";
import MenuModel from "./MenuModel";
import MenuView from "./MenuView";

export default class MenuController extends Controller{

    private view:MenuView
    private model:MenuModel
    private catAni:dragonBones.ArmatureDisplay
    private stageIdx:number=0
    private colorCur:string //当前选择的色彩   
    private answers:string[] 
    private camera:cc.Camera

    constructor(){
        super();
    }
    public static get Inst(): MenuController {
        if (this._inst == null) {
            this._inst = new MenuController()
        }
        return this._inst
    }

    public async init(): Promise<void> {
        cc.macro.CLEANUP_IMAGE_CACHE = false;
        this.model=new MenuModel(this);
        await this.model.init();

        this.view=await this.getView(ViewConst.MenuView,MenuView) as MenuView;
        await this.view.updateData();
        this.view.open();

        let gameData=this.model.getItem(this.stageIdx);
        
        let words=gameData.words.split("");
        let answers=gameData.answers.split("");
        let itemAudio=gameData.audio_url;
        this.answers=new Array();
        cc.log(words);
        cc.log(answers);
        let colorBlocks=this.view.colorItems;
        for(let i=0;i<colorBlocks.length;i++){
            cc.log(colorBlocks[i].name);
            let word=colorBlocks[i].getComponentInChildren(cc.Label);
            word.string=words[i];
            colorBlocks[i].color=cc.Color.WHITE;
            // colorBlocks[i].getComponent(cc.Sprite).trim=true;
            colorBlocks[i].on(cc.Node.EventType.TOUCH_START,()=>{
                if(GameUtil.isEmptyObj(this.colorCur))
                {
                    return;
                }
                // this.onClickBlock(i,answers);
                let result=answers.findIndex((item)=>{
                    return item==i.toString();
                });
                cc.log("i:"+i+",result:"+result)
                if(result==-1){
                    this.onWrong();
                }
                else{
                    this.answers[result]=i.toString();
                    let color=new cc.Color();
                    color.fromHEX(this.colorCur);
                    colorBlocks[i].color=color;
                    // cc.Color.fromHEX(colorBlocks[i].color,+"#"+this.colorCur);
                    this.onRight(itemAudio);

                    let flag=0;
                    for(let i=0;i<this.answers.length;i++){
                        if(this.answers[i]==answers[i]){
                            flag++;
                        }                        
                    }
                    (flag>=answers.length)&&this.finish(colorBlocks);
                }
            });
            colorBlocks[i]._hitTest=this._hitTest.bind(this);
        }

        this.catAni=this.view.roleAnimation;

        let btnColors=this.view.btnColors
        for(let i=0;i<btnColors.length;i++){
            btnColors[i].addClickCb(()=>{
                this.onClickColor(btnColors[i].node)
            });
        }

        this.view.btnRole.addClickCb(this.onClickRole.bind(this));
        this.enter();
    }

    private onClickBlock(idx:number,answers:string[]){

    }

    private onClickColor(node:cc.Node){
        let choice=this.view.choiceColor;
        choice.active=true;
        choice.x=node.x;
        choice.y=node.y;
        let color=node.name;
        cc.log(color);
        AppFacade.getMgr(SoundMgr).playResEffect(ResConst.snd.click);
        this.colorCur=color;
    }

    private enter(){
        let gameData=this.model.getItem(this.stageIdx);        
        let itemAudio=gameData.audio_url;
        AppFacade.getMgr(SoundMgr).playEffectByUrl(itemAudio);
        // AppFacade.getMgr(SoundMgr).playEffectByUrl(this.model.getStartAudio());
        this.playDragonBoneAnimation(this.catAni,"begin",1,()=>{
            this.playDragonBoneAnimation(this.catAni,"normal",-1);
        });
    }

    private wait(){
        AppFacade.getMgr(SoundMgr).playEffectByUrl(this.model.getWaitAudio());
        this.playDragonBoneAnimation(this.catAni,"normal",-1);
    }

    private finish(colorBlocks){
        AppFacade.getMgr(SoundMgr).playResEffect(this.model.getFinishAudio());
        this.playDragonBoneAnimation(this.catAni,"finish",1);
        this.view.resultPaint.active=true;
        this.view.paint.active=false;
        
        let resultPaint=this.view.resultPaint.children[0];
        // let colorBlocks=this.view.colorItems;
        for(let i=0;i<colorBlocks.length;i++){
            // cc.log(colorBlocks[i].color);
            let word=colorBlocks[i].getComponentInChildren(cc.Label);
            // word.string=words[i];
            // colorBlocks[i].color=cc.Color.WHITE;

            let item=resultPaint.children[i];
            if(colorBlocks[i].color){
                item.color=colorBlocks[i].color;
            }
            else
            {
                item.color=cc.Color.WHITE
            }
            let w=item.getComponentInChildren(cc.Label);
            w.string=word.string;
            w.node.color=cc.Color.BLACK;
            
        }
    }

    private finishWait(){
        AppFacade.getMgr(SoundMgr).playEffectByUrl(this.model.getFinishWaitAudio());
        this.playDragonBoneAnimation(this.catAni,"normal",-1);
    }

    private onPaint(){
        AppFacade.getMgr(SoundMgr).playResEffect(ResConst.snd.painted);
    }

    private async onRight(){        
        AppFacade.getMgr(SoundMgr).playEffectByUrl(this.model.getFinishWaitAudio());
        this.playDragonBoneAnimation(this.catAni,"right",1);
        cc.log("Right")
    }

    private onWrong(){
        AppFacade.getMgr(SoundMgr).playResEffect(this.model.getFinishWaitAudio());
        this.playDragonBoneAnimation(this.catAni,"wrong",1);
        cc.log("Wrong")
    }

    private onClickRole(){
        AppFacade.getMgr(SoundMgr).playResEffect(ResConst.snd.click);

    }

    public release(): void {
        
    }

    private playDragonBoneAnimation(node, animationName, time = 1, onFinish = null, onFrameEvent = null) {
        const armatureDisplay = node.getComponent(dragonBones.ArmatureDisplay);
        armatureDisplay.once(dragonBones.EventObject.COMPLETE, () => {
          if (onFinish) {
            onFinish();
          }
        });
        armatureDisplay.on(dragonBones.EventObject.FRAME_EVENT, (event) => {
          if (onFrameEvent) {
            onFrameEvent(event);
          }
        });
        console.log('animationName = ' + animationName);
        console.log('time = ' + time);
        armatureDisplay.playAnimation(animationName, time);
        return armatureDisplay;
      }

      
	_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;
		}

		if (!this.camera) {
			const checkCameraNode = cc.find('Canvas/CheckCamera');
			if (!checkCameraNode) {
				throw '找不到[Canvas/CheckCamera]。';
			}
			this.camera = checkCameraNode.getComponent(cc.Camera);
		}
		if (this.camera.cullingMask != -2) {
			console.warn(`[${this.camera.cullingMask}]: 检查CheckCamera的cullingMask值，应该只选择camera`);
		}
		this.camera.node.active = true;
		let posInRect = cc.v2(
			(posInNode.x - offset.x + rect.width * sprite.anchorX),
			(posInNode.y - offset.y + rect.height * sprite.anchorY)
		);
		let tex = spriteFrame.getTexture();
		this.camera.enabled = true;
		let rt;
		let destory = false;
		if (tex instanceof cc.RenderTexture) {
			rt = tex;
		} else {
			rt = new cc.RenderTexture()
			rt.initWithSize(tex.width, tex.height, cc.gfx.RB_FMT_S8);
			rt.drawTextureAt(tex, 0, 0);
			destory = true;
		}
		// data就是这个texture的rgba值数组
		this.camera.targetTexture = rt;
		this.camera.render(undefined);
		let data;
		//图集里的图片可能会旋转
		if (spriteFrame.isRotated()) {
			data = rt.readPixels(null, rect.x + posInRect.y, rect.y + posInRect.x, 1, 1);
		} else {
			data = rt.readPixels(null, rect.x + posInRect.x, rect.y + rect.height - posInRect.y, 1, 1);
		}
		this.camera.targetTexture = null;
		this.camera.enabled = false;
		this.camera.node.active = false;

		if (destory) {
			rt.destroy();
		}

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