import cocotb
from cocotb.handle import Immediate

from cocotb.clock import Clock
from cocotb.triggers import Timer, RisingEdge

from cocotbext.axi.apb import ApbMaster, ApbBus
from cocotbext.axi import AxiMaster, AxiBus, AxiLiteBus, AxiLiteRam



CLK_PERIOD = 5


@cocotb.test
async def test_sanity(dut):
    print("Hello world")
    cocotb.start_soon(Clock(dut.clk, CLK_PERIOD, unit="ns").start())

    s_apb = ApbMaster(ApbBus.from_prefix(dut.s_apb, ""), dut.clk, dut.rst)

    s_axi = AxiMaster(AxiBus.from_prefix(dut.s_axi, ""), dut.clk, dut.rst)
    m_axil = AxiLiteRam(AxiLiteBus.from_prefix(dut.m_axil, ""), dut.clk, dut.rst, size=2**32)

    m_axil.write(0, b"Hello, world!")


    dut.rst.value = Immediate(1)
    for _ in range(10):
        await RisingEdge(dut.clk)
    dut.rst.value = 0
    for _ in range(10):
        await RisingEdge(dut.clk)

    # await s_axi.write(0x200, [0x58, 0xa9, 0x00, 0x1a, 0xcb, 0x4c, 0x03, 0x02])
    await s_axi.write(0x200, [0xAD, 0x00, 0xE0, 0xAD, 0x01, 0xE0, 0xAD, 0x02, 0xE0, 0xAD, 0x03, 0xE0, 0xAD, 0x04, 0xE0, 0xCB])
    
    cocotb.start_soon(s_axi.read(0x200, 8))

    await Timer(10, "us")

    await s_apb.write_dword(0x0, 0)

    await Timer(1, "us")

    dut.i_nmi_ext.value = Immediate(1)

    await Timer(1, "us")