package com.example.Models.Expressions;

import com.example.Exceptions.BaseException;
import com.example.Models.Program.IDictionary;
import com.example.Models.Program.IHeap;
import com.example.Models.Types.IType;
import com.example.Models.Types.ReferenceType;
import com.example.Models.Values.IValue;
import com.example.Models.Values.ReferenceValue;

public class ReadHeap implements IExpression {
    private IExpression expression;

    public ReadHeap(IExpression expression) {
        this.expression = expression;
    }

    public String toString() {
        return "rH(" + expression + ")";
    }
    public IValue evaluate(IDictionary<String, IValue> table, IHeap heap) throws BaseException {
        IValue value = this.expression.evaluate(table, heap);
        if(!(value instanceof ReferenceValue)) {
            throw new BaseException("Expression is not a reference value");
        }
        int address = ((ReferenceValue)value).getAddress();
        if(!heap.contains(address)) {
            throw new BaseException("Address " + address + " is not in the heap");
        }
        return heap.get(address);
    }

    public IExpression copy() {
        return new ReadHeap(this.expression.copy());
    }

    public IType typeCheck(IDictionary<String, IType> typeTable) throws BaseException {
        IType type = this.expression.typeCheck(typeTable);
        if(!(type instanceof ReferenceType)) {
            throw new BaseException("Expression is not a reference value");
        }
        return ((ReferenceType)type).getInnerType();
    }
}
