#ifndef _MEMORY_WITH_HTIF_
#define _MEMORY_WITH_HTIF_

#include "iss/arch/riscv_hart_common.h"
#include "iss/vm_types.h"
#include <util/logging.h>
#include <util/sparse_array.h>
#include "../mem/memory_if.h"

namespace iss {
namespace mem {
template <typename WORD_TYPE> struct memory_with_htif : public memory_elem {
    using this_class = memory_with_htif<WORD_TYPE>;
    constexpr static unsigned WORD_LEN = sizeof(WORD_TYPE) * 8;

    memory_with_htif(arch::priv_if<WORD_TYPE> hart_if)
    : hart_if(hart_if) {}

    ~memory_with_htif() = default;

    memory_if get_mem_if() override {
        return memory_if{.rd_mem{util::delegate<rd_mem_func_sig>::from<this_class, &this_class::read_mem>(this)},
                         .wr_mem{util::delegate<wr_mem_func_sig>::from<this_class, &this_class::write_mem>(this)}};
    }

    void set_next(memory_if) override {
        // intenrionally left empty, leaf element
    }

private:
    iss::status read_mem(iss::access_type access, uint64_t addr, unsigned length, uint8_t* data) {
        for(auto offs = 0U; offs < length; ++offs) {
            *(data + offs) = mem[(addr + offs) % mem.size()];
        }
        return iss::Ok;
    }

    iss::status write_mem(iss::access_type access, uint64_t addr, unsigned length, uint8_t const* data) {
        mem_type::page_type& p = mem(addr / mem.page_size);
        std::copy(data, data + length, p.data() + (addr & mem.page_addr_mask));
        // this->tohost handling in case of riscv-test
        // according to https://github.com/riscv-software-src/riscv-isa-sim/issues/364#issuecomment-607657754:
        if(access && iss::access_type::FUNC && addr == hart_if.tohost) {
            return hart_if.exec_htif(data);
        }
        return iss::Ok;
    }

protected:
    using mem_type = util::sparse_array<uint8_t, 1ULL << 32>;
    mem_type mem;
    arch::priv_if<WORD_TYPE> hart_if;
};
} // namespace mem
} // namespace iss
#endif // _MEMORY_WITH_HTIF_
