import { ecs } from "../../../../../extensions/oops-plugin-framework/assets/libs/ecs/ECS";
import { SingletonModuleComp, smc } from "../../common/SingletonModuleComp";
import { Puppet } from "../../puppet/puppet";
import { PuppetViewComp } from "../../puppet/view/PuppetViewComp";
import { Checkpoint } from "../Checkpoint";
import { CheckpointModelComp } from "../model/CheckpointModel";

/**
 * 换肤
 */
@ecs.register('SkinChange')
export class SkinChangeComp extends ecs.Comp {

    skinId: number = 1

    reset() {
        this.skinId = 1
    }
}


export class SkinChangeSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {

    filter(): ecs.IMatcher {
        return ecs.allOf(CheckpointModelComp, SkinChangeComp);
    }

    entityEnter(e: Checkpoint): void {
       const nodes =  this.findAllNodesWithComponent(e.CheckpointView.node,PuppetViewComp)
       nodes.forEach(val => {
            const view:PuppetViewComp = val.getComponent(PuppetViewComp) 
            if(view){
                const skinComp = e.get(SkinChangeComp);
                (view.ent as Puppet).changeSkin(skinComp.skinId);
                ecs.getSingleton(SingletonModuleComp).account.AccountModel.skin = skinComp.skinId
            }
        })
        e.remove(SkinChangeComp)
    }

    findAllNodesWithComponent(root, component, nodes = []) {
        if (root.getComponent(component)) {
            nodes.push(root);
        }
        root.children.forEach(child => {
            this.findAllNodesWithComponent(child, component, nodes);
        });
        return nodes;
    }

}