defmodule Drab.Controller do
  @moduledoc """
  Set up Drab options for pages generated by the controller.

  By default Drab searches for the Commander with the name corresponding to the Controller,
  eg. NameController - NameCommander. You may specify the commander module by using `commander`
  or `commanders` option:

      use Drab.Controller, commander: MyApp.NameCommander

  See also `Drab.Commander`
  """

  require Logger

  defmacro __using__(options) do
    if options == [] do
      Logger.warn("`use Drab.Controller` without options is not mandatory (#{__CALLER__.module})")
    end

    quote bind_quoted: [options: options] do
      Module.put_attribute(__MODULE__, :__drab_opts__, options)

      unless Module.defines?(__MODULE__, {:__drab__, 0}) do
        def __drab__() do
          commander = Drab.Config.default_commander_for(__MODULE__)
          view = Drab.Config.default_view_for(commander)

          Enum.into(@__drab_opts__, %{
            commanders: [],
            commander: commander,
            view: view,
            controller: __MODULE__
          })
        end
      end
    end
  end
end
