package wacc

import cats.effect.Resource
import java.nio.charset.StandardCharsets
import java.io.BufferedWriter
import java.io.FileWriter
import cats.data.Chain
import cats.effect.IO

import org.typelevel.log4cats.Logger
import java.nio.file.Path

object writer {
  import assemblyIR._

  // TODO: Judging from documentation it seems as though IO.blocking is the correct choice
  // But needs checking

  /** Creates a resource safe BufferedWriter */
  private def bufferedWriter(outputPath: Path): Resource[IO, BufferedWriter] =
    Resource.make {
      IO.blocking(new BufferedWriter(new FileWriter(outputPath.toFile, StandardCharsets.UTF_8)))
    } { writer =>
      IO.blocking(writer.close())
        .handleErrorWith(_ => IO.unit) // TODO: ensures writer is closed even if an error occurs
    }

  /** Write line safely into a BufferedWriter */
  private def writeLines(writer: BufferedWriter, lines: Chain[AsmLine]): IO[Unit] =
    IO.blocking {
      lines.iterator.foreach { line =>
        writer.write(line.toString)
        writer.newLine()
      }
    }

  /** Main function to write assembly to a file */
  def writeTo(asmList: Chain[AsmLine], outputPath: Path)(using logger: Logger[IO]): IO[Unit] =
    bufferedWriter(outputPath).use {
      writeLines(_, asmList)
    }
}
