import FSprite from "../../FSprite";
import BehaviorNode from "./BehaviorNode";
/**
 * 行为树
 */
const {ccclass, property} = cc._decorator;
/**
 * 执行结果
 */
export const ExeResult = cc.Enum({
    Success: 0,
    Failure: 1,
    Running: 2,
});


@ccclass
export default class BehaviorTree extends cc.Component {

    public sprite:FSprite = null;//行为对象

    public rootNode:BehaviorNode;
    /**
     * 当前执行状态
     */
    public state = ExeResult.Success;
    /**
     * update(dt) 中执行
     * @returns 
     */
    public exec(){
        if(this.state == ExeResult.Running){
            return
        }
        this.state = ExeResult.Running
        this.executing(this.rootNode)
    }
    /**
     * 执行当前行为树
     */
    private executing(rootNode:BehaviorNode){
        let behaviorNode:BehaviorNode = this.findNode(rootNode);
        if(behaviorNode){
            behaviorNode.run((nextNode)=>{
                if(nextNode){
                    this.executing(nextNode)
                }else{
                    this.state = ExeResult.Success;
                }
            })
        }else{
            this.state = ExeResult.Success;
        }
    }
    /**
     * 递归查询当前行为树中可执行节点
     * @param node 
     * @returns 
     */
    private findNode(node:BehaviorNode):BehaviorNode{
        let nodes = node.childNode
        for (let i = 0; i < nodes.length; i++) {
            const element = nodes[i];
            if(element.isOK()){
                return element
            }else{
                this.findNode(element)
            }
        }
        return null
    }

}
