require "dunlop/generators"
require "dunlop/generators/generator_helpers"
require "csv_builder"

class Dunlop::TargetFileGenerator < Rails::Generators::NamedBase
  include Dunlop::Generators::GeneratorHelpers
  source_root File.expand_path('../templates', __FILE__)

  def create_target_file
    add_to_symbol_list "app/models/target_file.rb", 'setup_target_files', file_name

    template "model.rb.erb", "app/models/target_file/#{file_name}.rb"
    template "model_spec.rb.erb", "spec/models/target_file/#{file_name}_spec.rb"
    template "csv_builder.rb.erb", "app/csv_builders/target_file/#{file_name}_csv_builder.rb"
  end

  def add_factory
    if behavior == :revoke
      gsub_file "spec/factories/target_files.rb", /^s+factory 'target_file/#{file_name}'.*$/, ''
    else
      gsub_file "spec/factories/target_files.rb", /end\s*\z/m do |match_data|
        "  factory 'target_file/#{file_name}', class: 'TargetFile::#{class_name}', parent: :target_file\nend"
      end
    end
  end

  def add_translations
    gsub_file "config/locales/target_files.yml", /^      plural:\s*$/, "      target_file/#{file_name}: #{file_name.humanize}\n      plural:"
    gsub_file "config/locales/target_files.yml", /^    attributes:\s*$/, "        target_file/#{file_name}: #{file_name.humanize.pluralize}\n    attributes:"
  end
end
