#!/usr/bin/env python3

#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2021 Gwenhael Goavec-Merou <gwenhael.goavec-merou@trabucayre.com>
# SPDX-License-Identifier: BSD-2-Clause

import os

from migen import *

from litex.gen import *

from litex_boards.platforms import quicklogic_quickfeather

from litex.soc.integration.soc import SoCRegion
from litex.soc.integration.soc_core import *
from litex.soc.integration.builder import *
from litex.soc.cores.led import LedChaser
from litex.soc.cores.gpio import *

# CRG ----------------------------------------------------------------------------------------------

class _CRG(LiteXModule):
    def __init__(self, platform, with_eos_s3=False):
        self.rst    = Signal()
        self.cd_sys = ClockDomain()

        # # #

        if with_eos_s3:
            # Use clocks generated by the EOS-S3 CPU.
            self.comb += ClockSignal("sys").eq(ClockSignal("eos_s3_0"))
            self.comb += ResetSignal("sys").eq(ResetSignal("eos_s3_0") | self.rst)
        else:
            # Use clocks generated by the qlal4s3b_cell_macro.
            class Open(Signal): pass
            self.specials += Instance("qlal4s3b_cell_macro",
                o_Sys_Clk0     = self.cd_sys.clk,
                o_Sys_Clk0_Rst = self.cd_sys.rst,
                o_Sys_Clk1     = Open(),
                o_Sys_Clk1_Rst = Open(),
            )

# BaseSoC ------------------------------------------------------------------------------------------

class BaseSoC(SoCCore):
    def __init__(self, sys_clk_freq=10e6, with_led_chaser=True, with_gpio_in=True, **kwargs):
        platform = quicklogic_quickfeather.Platform()

        # CRG --------------------------------------------------------------------------------------
        self.crg = _CRG(platform, with_eos_s3=kwargs["cpu_type"] == "eos_s3")

        # SoCCore ----------------------------------------------------------------------------------
        kwargs["with_uart"] = False
        if kwargs.get("cpu_type", None) == "eos_s3":
            kwargs["integrated_sram_size"] = 0
        SoCCore.__init__(self, platform, sys_clk_freq, ident="LiteX SoC on QuickLogic QuickFeather", **kwargs)

        # EOS-S3 Integration -----------------------------------------------------------------------
        if kwargs.get("cpu_type", None) == "eos_s3":
            # in fact SRAM starts at 0x2000_0000 - but for some reason
            # this does not work and most QORC SDK linker scripts
            # use 0x2002_7000 + 0x0003_c800
            self.bus.add_region("sram", SoCRegion(
                origin = 0x2002_7000,
                size   = 0x0003_c800)
            )
            self.bus.add_region("rom", SoCRegion(
                origin = self.mem_map["rom"],
                size   = 4 * 128 * 1024,
                linker = True)
            )

        # Leds -------------------------------------------------------------------------------------
        if with_led_chaser:
            self.leds = LedChaser(
                pads         = platform.request_all("user_led"),
                sys_clk_freq = sys_clk_freq)

        # GPIOIn (Interrupt test) ------------------------------------------------------------------
        if with_gpio_in:
            self.gpio = GPIOIn(platform.request_all("user_btn_n"), with_irq=True)
            if kwargs["cpu_type"] == "eos_s3":
                self.irq.add("gpio", use_loc_if_exists=True)

# Build --------------------------------------------------------------------------------------------

def main():
    from litex.build.parser import LiteXArgumentParser
    parser = LiteXArgumentParser(platform=quicklogic_quickfeather.Platform, description="LiteX SoC on QuickLogic QuickFeather.")
    parser.set_defaults(cpu_type="eos_s3")
    args = parser.parse_args()

    soc = BaseSoC(**parser.soc_argdict)
    builder = Builder(soc)
    if args.cpu_type == "eos_s3":
        libeos_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "libeos")
        if not os.path.exists(libeos_path):
            os.system("wget -nc https://github.com/litex-hub/litex-boards/files/7880350/libeos.zip")
            os.system(f"unzip libeos.zip -d {libeos_path}")
        builder.add_software_package("libeos", src_dir=libeos_path)
        builder.add_software_library("libeos")
    if args.build:
        builder.build(**parser.toolchain_argdict)


if __name__ == "__main__":
    main()
