class Condition extends Node {
    constructor(myself, shieldFilter = false, rangeFilter = false, shield, range) { //shieldFilter : true/false - rangeFilter : true/false
        super("condition");
        this.shieldFilter = shieldFilter;
        this.rangeFilter = rangeFilter;
        this.shield = shield;
        this.range = range;
        this.myself = myself; //true = myself / false = enemyBot;

        this.lNode = [];
    }

    addNode(node) {
        this.lNode.push(node);
    }

    do(robot) {
        if (this.doCondition(robot)) {
            for (let i = 0; i < this.lNode.length; i++) {
                if (this.lNode[i].do(robot)) {
                    return true;
                }
            }
        }
        return false;
    }

    doCondition(robot) {
        if (this.shieldFilter) {
            return this.shieldCondition(robot);
        } else if (this.rangeFilter) {
            return this.rangeCondition(robot);
        }
        return false;
    }

    rangeCondition(robot) {
        if (robot.haveTarget()) {
            if (this.myself) {
                return robot.calcDistance(robot.target) <= robot.range * RANGE * this.range;
            } else {
                return robot.target.calcDistance(robot) <= robot.target.range * RANGE * this.range;
            }
        }
        return false;
    }

    shieldCondition(robot) {
        if (this.myself) {
            return this.verifyShield(robot);
        } else {
            if (robot.haveTarget())
                return this.verifyShield(robot.target);
            return false;
        }
    }

    verifyShield(target) {
        return target.shield.getValue() / target.shield.valueMax <= this.shield;

    }

    clearNodes() {
        this.lNode = [];
    }


    moveToward(robot) {
        return robot.advanceToTarget();
    }

    fleeFrom(robot) {
        return robot.fleeFromTarget();
    }

    getFrame() {
        let line;
        if (this.myself) {
            line = 0;
        } else {
            line = 1;
        }
        let image = 0;
        if (this.shieldFilter) { //shield
            image = Math.floor(this.shield * 3);
        } else {
            if (this.rangeFilter) { //range
                image = 4 + Math.floor(this.range * 3 - 1);
            }
        }
        return line * 7 + image;
    }

    getTreeJson() {
        let json = super.getTreeJson(this.getOptionJson());
        json = json.substr(0, json.length - 1) + ',';
        json += '"lNode":[';
        this.lNode.forEach(node => json += node.getTreeJson() + ',');
        json = endLineJson(json);
        json += ']}'
        return json;
    }

    getOptionJson() {
        return this.myself + ',' + this.shieldFilter + ',' + this.rangeFilter + ',' + this.shield + ',' + this.range;
    }
}