defmodule Mix.Tasks.Pyro.Generators.CSS do
  @moduledoc false

  import Pyro.ComponentLibrary.TemplateHelpers

  require EEx

  def generate(module, _opts \\ []) do
    path = Pyro.Info.css_output_path(module)

    if path do
      path = Path.relative_to_cwd(path)
      File.mkdir_p!(path)
      generated_file = Path.join(path, "#{module |> Module.split() |> Enum.join()}.css")
      File.write!(generated_file, gen_module(module))
    end
  end

  def render_module(assigns) do
    EEx.eval_string(
      ~E'''
      /*
        WARNING: THIS FILE WAS AUTOMATICALLY GENERATED BY PYRO. DO NOT EDIT DIRECTLY.
        INSTEAD, CONFIGURE <%= @source_file %>
      */

      <%= for class <- @classes do %>
      /* <%= class.template.file %>:<%= class.template.line %> */
      <%= class.template.rendered %>
      <% end %>
      ''',
      assigns: assigns
    )
  end

  defp gen_module(module) do
    # classes = Pyro.Info.all_classes_for_strategy(module)
    classes = []
    source_file = Path.relative_to_cwd(module.__info__(:compile)[:source])

    render_module(source_file: source_file, classes: classes)
  end
end
