
#include <memory>
#include "Evaluator.hpp"
#include "EvaluationException.hpp"
#include "EvaluationScope/EvaluationScope.hpp"
#include "EvalValues/ScriptFunctionEvalValue.hpp"
#include "EvalValues/TableEvalValue.hpp"
#include "../Binder/BoundExpressions/BoundTableExpression.hpp"
#include "../Binder/BoundExpressions/BoundFunctionCallExpression.hpp"
#include "../Binder/BoundExpressions/BoundRequireExpression.hpp"
#include "../ScriptTypes/TableScriptType.hpp"
#include "../UserData/UserDataFunction.hpp"
#include "EvalValues/NumericalTableEvalValue.hpp"

using namespace std;
using namespace Porygon::Binder;

namespace Porygon::Evaluation {
    const EvalValue* Evaluator::Evaluate(const BoundScriptStatement *statement) {
        this->_evaluationScope = make_shared<EvaluationScope>(this->_scriptVariables);
        auto statements = statement->GetStatements();
        if (statements -> size() == 1 && statements->at(0)->GetKind() == BoundStatementKind::Expression){
            auto expStatement = (BoundExpressionStatement*) statements -> at(0);
            return this -> EvaluateExpression(expStatement -> GetExpression()).Clone();
        }
        EvaluateBlockStatement(statement);
        if (this->_returnValue.Get() == nullptr){
            return nullptr;
        }
        return this->_returnValue.Clone();
    }

    void Evaluator::EvaluateStatement(const BoundStatement *statement) {
        if (this->_hasReturned)
            return;
        switch (statement->GetKind()) {
            case BoundStatementKind::Script:
                throw; // Should never happen
            case BoundStatementKind::Block:
                return this->EvaluateBlockStatement((BoundBlockStatement*)statement);
            case BoundStatementKind::Expression:
                return this->EvaluateExpressionStatement((BoundExpressionStatement *) statement);
            case BoundStatementKind::Assignment:
                return this->EvaluateAssignmentStatement((BoundAssignmentStatement *) statement);
            case BoundStatementKind::IndexAssignment:
                return this->EvaluateIndexAssignmentStatement((BoundIndexAssignmentStatement *) statement);
            case BoundStatementKind::FunctionDeclaration:
                return this->EvaluateFunctionDeclarationStatement((BoundFunctionDeclarationStatement *) statement);
            case BoundStatementKind::Return:
                return this->EvaluateReturnStatement((BoundReturnStatement *) statement);
            case BoundStatementKind::Conditional:
                return this->EvaluateConditionalStatement((BoundConditionalStatement *) statement);
            case BoundStatementKind::NumericalFor:
                return this->EvaluateNumericalForStatement((BoundNumericalForStatement*)statement);
            case BoundStatementKind::GenericFor:
                return this-> EvaluateGenericForStatement((BoundGenericForStatement*)statement);
            case BoundStatementKind::While:
                return this-> EvaluateWhileStatement((BoundWhileStatement*)statement);

            case BoundStatementKind::Break:
                this -> _hasBroken = true;
                return;
            case BoundStatementKind::Bad:
                throw;
        }
        throw EvaluationException("Evaluating this statement is not supported");
    }

    void Evaluator::EvaluateBlockStatement(const BoundBlockStatement *statement) {
        for (auto s: *statement->GetStatements()) {
            this->EvaluateStatement(s);
            if (this->_hasReturned)
                break;
        }
    }

    void Evaluator::EvaluateExpressionStatement(const BoundExpressionStatement *statement) {
        this->EvaluateExpression(statement->GetExpression());
    }

    void Evaluator::EvaluateAssignmentStatement(const BoundAssignmentStatement *statement) {
        auto value = this->EvaluateExpression(statement->GetExpression());
        auto key = statement->GetKey();
        if (key->IsCreation()) {
            this->_evaluationScope->CreateVariable(key, value.Clone());
        } else {
            this->_evaluationScope->SetVariable(key, value.Clone());
        }
    }

    void Evaluator::EvaluateIndexAssignmentStatement(const BoundIndexAssignmentStatement *statement) {
        auto indexExpression = statement->GetIndexExpression();
        auto value = this->EvaluateExpression(statement->GetValueExpression());
        auto index = ((BoundIndexExpression *) indexExpression);
        auto table = this->EvaluateExpression(index->GetIndexableExpression());
        auto key = this->EvaluateExpression(index->GetIndexExpression());
        table->SetIndexValue(key.Get(), value.Take());
    }

    void Evaluator::EvaluateFunctionDeclarationStatement(const BoundFunctionDeclarationStatement *statement) {
        auto type = statement->GetType();
        auto key = statement->GetKey();
        auto block = statement->GetBlock();
        auto option = new Evaluation::EvaluationScriptFunctionOption(block, this->_evaluationScope);

        if (key->IsCreation()) {
            auto p = new GenericFunctionEvalValue(type, Utilities::Random::Get());
            p->RegisterOption(option);
            auto value = EvalValuePointer(p);
            this->_evaluationScope->CreateVariable(key, value);
        } else {
            auto var = (GenericFunctionEvalValue*)this -> _evaluationScope ->GetVariable(key).Take();
            var->RegisterOption(option);
            delete var;
        }
    }

    void Evaluator::EvaluateReturnStatement(const BoundReturnStatement *statement) {
        auto expression = statement->GetExpression();
        if (expression == nullptr) {
            this->_hasReturned = true;
            this -> _returnValue.ClearAssign(nullptr);
            return;
        }
        auto value = this->EvaluateExpression(expression).Take();
        this->_hasReturned = true;
        this->_returnValue.ClearAssign(value);
    }

    void Evaluator::EvaluateConditionalStatement(const BoundConditionalStatement *statement) {
        auto condition = statement->GetCondition();
        if (EvaluateExpression(condition)->EvaluateBool()) {
            this->EvaluateStatement(statement->GetBlock());
        } else {
            auto elseStatement = statement->GetElseStatement();
            if (elseStatement != nullptr) {
                this->EvaluateStatement(elseStatement);
            }
        }
    }

    void Evaluator::EvaluateNumericalForStatement(const BoundNumericalForStatement *statement) {
        long start = this->EvaluateExpression(statement -> GetStart()) -> EvaluateInteger();
        long end = this->EvaluateExpression(statement -> GetEnd()) -> EvaluateInteger();
        long step = 1;
        auto stepExp = statement -> GetStep();
        if (stepExp != nullptr){
            step = this -> EvaluateExpression(stepExp) -> EvaluateInteger();
        }
        auto identifier = statement -> GetIdentifier();
        this -> _evaluationScope -> CreateVariable(identifier, nullptr);
        auto block = (BoundBlockStatement*)statement -> GetBlock();
        auto statements = *block -> GetStatements();
        if (step >= 0){
            for (long i = start; i <= end; i += step){
                this -> _evaluationScope -> SetVariable(identifier, new IntegerEvalValue(i));
                for (auto s: statements) {
                    this->EvaluateStatement(s);
                    if (this->_hasReturned || this -> _hasBroken)
                        break;
                }
                if (this->_hasReturned || this -> _hasBroken)
                    break;
            }
        } else{
            for (long i = start; i >= end; i += step){
                this -> _evaluationScope -> SetVariable(identifier, new IntegerEvalValue(i));
                for (auto s: statements) {
                    this->EvaluateStatement(s);
                    if (this->_hasReturned || this -> _hasBroken)
                        break;
                }
                if (this->_hasReturned || this -> _hasBroken)
                    break;
            }
        }
        this -> _hasBroken = false;
    }

    void Evaluator::EvaluateGenericForStatement(const BoundGenericForStatement *statement) {
        auto iteratorVal = EvaluateExpression(statement -> GetIterator());
        auto iterator = iteratorVal -> GetKeyIterator();
        auto keyVariable = statement ->GetKeyIdentifier();
        auto valueVariable = statement ->GetValueIdentifier();

        this -> _evaluationScope -> CreateVariable(keyVariable, nullptr);
        if (valueVariable != nullptr)
            this -> _evaluationScope -> CreateVariable(valueVariable, nullptr);
        auto block = (BoundBlockStatement*)statement -> GetBlock();
        auto statements = *block -> GetStatements();
        while (iterator->MoveNext()){
            auto currentKey = EvalValuePointer(iterator->GetCurrent());
            this -> _evaluationScope -> SetVariable(keyVariable, currentKey);
            if (valueVariable != nullptr){
                auto currentValue = EvalValuePointer(iteratorVal -> IndexValue(currentKey.Get()));
                this -> _evaluationScope -> SetVariable(valueVariable, currentValue);
            }
            for (auto s: statements) {
                this->EvaluateStatement(s);
                if (this->_hasReturned || this -> _hasBroken)
                    break;
            }
            if (this->_hasReturned || this -> _hasBroken)
                break;
        }
        this -> _hasBroken = false;
        delete iterator;
    }

    void Evaluator::EvaluateWhileStatement(const BoundWhileStatement *statement) {
        auto condition = statement -> GetCondition();
        auto block = (BoundBlockStatement*)statement -> GetBlock();
        auto statements = *block -> GetStatements();
        while (this->EvaluateExpression(condition)->EvaluateBool()){
            for (auto s: statements) {
                this->EvaluateStatement(s);
                if (this->_hasReturned || this -> _hasBroken)
                    break;
            }
            if (this->_hasReturned || this -> _hasBroken)
                break;
        }
        this -> _hasBroken = false;
    }

    /////////////////
    // Expressions //
    /////////////////

    EvalValuePointer Evaluator::EvaluateExpression(const BoundExpression *expression) {
        switch (expression->GetKind()){

            case BoundExpressionKind::Bad: throw;
            case BoundExpressionKind::LiteralInteger:
                return new IntegerEvalValue(((BoundLiteralIntegerExpression *) expression)->GetValue());
            case BoundExpressionKind::LiteralFloat:
                return new FloatEvalValue(((BoundLiteralFloatExpression *) expression)->GetValue());
            case BoundExpressionKind::LiteralString:
                return new StringEvalValue(*((BoundLiteralStringExpression *) expression)->GetValue());
            case BoundExpressionKind::LiteralBool:
                return new BooleanEvalValue(((BoundLiteralBoolExpression *) expression)->GetValue());
            case BoundExpressionKind::Variable:
                return this -> GetVariable((BoundVariableExpression*)expression);
            case BoundExpressionKind::Unary:
                return this->EvaluateUnary((BoundUnaryExpression *) expression);
            case BoundExpressionKind::Binary:
                return this->EvaluateBinary((BoundBinaryExpression *) expression);
            case BoundExpressionKind::FunctionCall:
                return this->EvaluateFunctionCallExpression(expression);
            case BoundExpressionKind::Index:
                return this->EvaluateIndexExpression(expression).Take();
            case BoundExpressionKind::PeriodIndex:
                return this->EvaluatePeriodIndexExpression(expression);
            case BoundExpressionKind::NumericalTable:
                return this->EvaluateNumericTableExpression(expression);
            case BoundExpressionKind::Table:
                return this->EvaluateComplexTableExpression(expression);
            case BoundExpressionKind::Require:
                return this -> EvaluateRequireExpression(expression);
        }
    }

    EvalValuePointer Evaluator::EvaluateBinary(const BoundBinaryExpression *expression){
        auto leftValue = this -> EvaluateExpression(expression->GetLeft());
        auto rightValue = this -> EvaluateExpression(expression->GetRight());
        auto operation = expression->GetOperation();
        if (operation == BoundBinaryOperation::Equality){
            return new BooleanEvalValue(leftValue == rightValue);
        } else if (operation == BoundBinaryOperation::Inequality){
            return new BooleanEvalValue(leftValue != rightValue);
        }
        return leftValue->BinaryOperation(operation, rightValue.Get());
    }

    EvalValuePointer Evaluator::EvaluateUnary(const BoundUnaryExpression *expression) {
        auto exp = expression->GetOperand();
        auto val = EvaluateExpression(exp);
        return val->UnaryOperation(expression->GetOperation());
    }

    EvalValuePointer Evaluator::GetVariable(const BoundVariableExpression *expression) {
        auto variable = this->_evaluationScope->GetVariable(expression->GetKey());
        if (variable.Get() == nullptr) {
            throw EvaluationException("Variable not found");
        }
        return variable;
    }

    EvalValuePointer Evaluator::EvaluateFunctionCallExpression(const BoundExpression *expression) {
        auto functionCall = (BoundFunctionCallExpression *) expression;
        auto function = (GenericFunctionEvalValue*)this->EvaluateExpression(functionCall->GetFunctionExpression()).Clone();

        auto boundParameters = functionCall->GetParameters();
        auto parameters = vector<EvalValuePointer>(boundParameters->size());
        for (size_t i = 0; i < boundParameters->size(); i++) {
            parameters[i] = this->EvaluateExpression(boundParameters->at(i));
        }

        auto type = std::dynamic_pointer_cast<const GenericFunctionScriptType>(function->GetType());
        auto func = function;
        auto option = functionCall ->GetFunctionOption();
        auto opt = func->GetOption(option->GetOptionId());
        if (option -> IsScriptFunction()){
            auto parameterTypes = option->GetParameterTypes();
            auto scriptFunctionType = dynamic_cast<const ScriptFunctionOption*>(option);
            auto parameterKeys = scriptFunctionType->GetParameterKeys();
            auto originalScope = this->_evaluationScope;
            auto scriptOption = dynamic_pointer_cast<const EvaluationScriptFunctionOption>(opt);
            this->_evaluationScope = scriptOption->GetScope();

            for (int i = 0; i < parameterTypes.size() && i < parameterKeys.size() && i < parameters.size(); i++) {
                auto parameter = parameters[i];
                auto key = parameterKeys.at(i);
                this->_evaluationScope->CreateVariable(key.get(), parameter.Clone());
            }
            this->EvaluateBlockStatement(scriptOption->GetInnerBlock().get());
            this->_evaluationScope = originalScope;

            this->_hasReturned = false;
            auto r = this->_returnValue;
            this->_returnValue.ClearAssign(nullptr);
            delete function;
            return r;
        } else{
            auto scriptOption = dynamic_pointer_cast<const UserData::UserDataFunction>(opt);
            const EvalValue* arr[parameters.size()];
            for (size_t i = 0; i < parameters.size(); i++){
                arr[i] = parameters[i].Get();
            }
            delete function;
            return scriptOption -> Call(this -> _scriptOptions, arr, parameters.size());
        }
    }

    const EvalValue* Evaluator::EvaluateFunction(const GenericFunctionEvalValue *function,
                                                            const vector<EvalValue *> &parameters) {
        auto type = function->GetType();
        auto option = dynamic_cast<const ScriptFunctionOption*>(type->GetFirstOption());

        auto parameterTypes = option->GetParameterTypes();
        auto parameterKeys = option->GetParameterKeys();

        auto originalScope = this->_evaluationScope;
        auto scriptOption = dynamic_pointer_cast<const EvaluationScriptFunctionOption>(function->GetOption(0));
        this->_evaluationScope = scriptOption->GetScope();

        for (int i = 0; i < parameterTypes.size() && i < parameterKeys.size() && i < parameters.size(); i++) {
            auto parameter = parameters[i];
            auto key = parameterKeys.at(i);
            this->_evaluationScope->CreateVariable(key.get(), parameter->Clone());
        }
        this->EvaluateBlockStatement(scriptOption->GetInnerBlock().get());
        this->_evaluationScope = originalScope;
        this->_hasReturned = false;
        auto r = this->_returnValue.Take();
        delete function;
        return r;
    }

    EvalValuePointer Evaluator::EvaluateIndexExpression(const BoundExpression *expression) {
        auto indexExpression = (BoundIndexExpression *) expression;
        auto index = this->EvaluateExpression(indexExpression->GetIndexExpression());
        auto indexable = this->EvaluateExpression(indexExpression->GetIndexableExpression());
        return indexable->IndexValue(index.Get());
    }

    EvalValuePointer Evaluator::EvaluatePeriodIndexExpression(const BoundExpression *expression) {
        auto indexExpression = (BoundPeriodIndexExpression *) expression;
        auto index = indexExpression->GetIndex()->GetHash();
        auto indexable = this->EvaluateExpression(indexExpression->GetIndexableExpression());
        return indexable->IndexValue(index);
    }

    EvalValuePointer Evaluator::EvaluateNumericTableExpression(const BoundExpression *expression) {
        auto tableExpression = (BoundNumericalTableExpression *) expression;
        auto valueExpressions = tableExpression->GetExpressions();
        auto values = new vector<EvalValuePointer>(valueExpressions->size());
        for (size_t i = 0; i < valueExpressions->size(); i++) {
            auto val = this->EvaluateExpression(valueExpressions->at(i));
            values->at(i) = val.Take();
        }
        auto valuesPointer = shared_ptr<vector<EvalValuePointer>>(values);
        return new NumericalTableEvalValue(valuesPointer);
    }

    EvalValuePointer Evaluator::EvaluateComplexTableExpression(const BoundExpression *expression) {
        auto tableExpression = (BoundTableExpression *) expression;
        const auto& baseType = tableExpression -> GetType();
        auto type = dynamic_pointer_cast<const TableScriptType>(baseType);
        auto declaredVars = type->GetValues();
        auto variables = make_shared<map<Utilities::HashedString, EvalValuePointer>>();
        for (const auto& i : *declaredVars) {
            variables->insert({i.first, nullptr});
        }
        auto evaluator = make_shared<EvaluationScope>(variables.get());
        auto currentEvaluator = this->_evaluationScope;
        this->_evaluationScope = evaluator;
        this->EvaluateBlockStatement(tableExpression->GetBlock());
        this->_evaluationScope = currentEvaluator;
        return new TableEvalValue(variables);
    }

    EvalValuePointer Evaluator::EvaluateRequireExpression(const BoundExpression* expression) {
        auto module = dynamic_cast<const BoundRequireExpression*>(expression)->GetModule();
        auto result = module->Evaluate();
        if (module ->GetReturnType() == nullptr){
            for (const auto& v: *module->GetScriptVariables()){
                this->_scriptVariables->at(v.first) = v.second.Clone();
            }
            return nullptr;
        } else{
            return result.Take();
        }
    }
}