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

    def copy_helper_files
      prefix = File.join "app", "helpers", module_path
      path = File.join prefix, "#{singularized_name}_helper.rb"
      base_path = File.join prefix, "base_helper.rb"

      template "base.rb", base_path unless File.exists?(base_path)
      template "item.rb", path
    end

    def inject_policy_path
      base_helper_path = File.join "app", "helpers", module_path, "base_helper.rb"
      base_helper_data = File.read base_helper_path
      policy_path_code = %Q{        #{full_class_name} => #{module_variable_name}_#{pluralized_name}_path,}
      parts = base_helper_data.split("\n")

      method_start_index = parts.index {|part| part.to_s.strip.index "add_sidebar"}
      return unless method_start_index

      method_end_index = parts[method_start_index..-1].index {|part| part.to_s.strip.index "}"}
      return unless method_end_index

      code_index = method_start_index + method_end_index
      injected_code = parts[0...code_index] + [policy_path_code] + parts[code_index..-1] + [""]

      File.write base_helper_path, injected_code.join("\n")
    end
  end
end
