package projet

import chisel3.simulator.scalatest.ChiselSim
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.must.Matchers
import java.nio.file.{Files, Paths}
import scala.jdk.CollectionConverters._
import scala.collection.mutable.ListBuffer
import java.nio.file.FileSystems
import java.nio.file.Path
import org.scalatest.ParallelTestExecution
import projet.ZzTopCommon.expectedValuesFromAsm
import projet.ZzTopCommon.expectNextValue

class ZzTopAllSpec
    extends AnyFreeSpec
    with Matchers
    with ParallelTestExecution
    with ChiselSim {

    // Fonction de test commune
    def testWith(file: String): Unit = {
        val path = file.replace("/mem/", "/").replace(".mem", ".s")
        if (Files.exists(Paths.get(path))) {
            val expected = expectedValuesFromAsm(path)
            val test_name = file.hashCode();

            simulate(
                new ZzTop(file, true),
                subdirectory = Some(test_name.toString())
            ) { dut =>
                val trace = ListBuffer[String]()
                expected.foreach { value =>
                    expectNextValue(dut, value, timeout = 100, trace)
                }
            }
        }
    }

    val dir =
        FileSystems.getDefault().getPath(sys.env("PROOT") + "/bench/mem/tests")

    var tests = Files
        .walk(dir)
        .iterator()
        .asScala
        .filter(path => path.getFileName().toString().split('.').last == "mem")
        .toArray[Path];

    for (t <- tests) {
        s"Sim ${t.toString()}" in {
            testWith(t.toString());
        }
    }
}
