module Admin
  class ViewsGenerator < Admin::GeneratorBase
    source_root File.expand_path("../templates", __FILE__)

    argument :attributes, type: :array, default: [], banner: "attribute1 attribute2 attribute3"

    def copy_view_files
      available_views.each do |view|
        filename = "#{view}.html.haml"
        template filename, File.join(path_prefix, pluralized_name, filename)
      end
    end

    def copy_partials
      template "_form.html.haml", File.join(path_prefix, pluralized_name, "_form.html.haml")
      template "_list.html.haml", File.join(path_prefix, pluralized_name, "_list.html.haml")
    end

    def append_sidebar
      sidebar_code = %Q{- register_sidebar #{module_variable_name}_sidebar\n}
      sidebar_path = "app/views/layouts/_sidebar.html.haml"
      sidebar_data = File.read sidebar_path

      already_exists = sidebar_data.index module_variable_name

      append_file sidebar_path, sidebar_code unless already_exists
    end

    def append_tabs
      tabs_code = %Q{  %li{class: active_tab("#{pluralized_name}")}\n    = link_to "#{pluralized_name.humanize}", #{module_variable_name}_#{pluralized_name}_path if policy(#{full_class_name}).allowed?\n}
      tabs_path = File.join(path_prefix, "_tabs.html.haml")

      copy_file "_tabs.html.haml", tabs_path unless File.exists?(tabs_path)
      append_file tabs_path, tabs_code
    end

    protected

    def path_prefix
      File.join "app", "views", module_path
    end

    def available_views
      %w(index edit show new)
    end
  end
end
