<?php


namespace Simnang\LoanPro\Utils\Parser\TreeGenerators;
use Simnang\LoanPro\Utils\Parser\Token;

/**
 * Class ExpressionTreeGenerator
 *
 * @package Simnang\LoanPro\Utils\Parser\TreeGenerators
 */
abstract class ExpressionTreeGenerator
{
    protected $tokenSymbols;
    protected $curTree = null;

    /**
     * Creates an expression tree generator
     * @param $tokenSymbols - tokens to use with their symbols
     */
    public function __construct($tokenSymbols){
        $this->tokenSymbols = $tokenSymbols;
    }

    public function __destruct(){
        $this->Reset();
    }

    private function CleanTree(ExpressionTreeNode $tree){
        if(!is_null($tree->leftNode))
            $this->CleanTree($tree->leftNode);
        if(!is_null($tree->rightNode))
            $this->CleanTree($tree->rightNode);
        $tree->parentNode = null;
    }

    /**
     * Process the next token
     * @param Token $t
     * @return mixed
     */
    public abstract function ProcessToken(Token $t);

    /**
     * Returns the final expression tree
     *  State becomes invalid after call
     * @return mixed
     */
    public abstract function GetExpressionTree();

    /**
     * Resets the expression tree generator
     * @return mixed
     */
    public function Reset(){
        if(!is_null($this->curTree))
            $this->CleanTree($this->curTree);
        $this->curTree = null;
    }
}