require 'fileutils'
class Dunlop::RenameSourceFileGenerator < Rails::Generators::NamedBase
  include Rails::Generators::Migration
  include Dunlop::Generators::GeneratorHelpers
  source_root File.expand_path('../templates', __FILE__)
  class_option :new_name, required: true

  def do_rename
    return if behavior == :revoke

    #new_source_file_path = path('app/models')
    #rename_model "source_file/#{file_name}", "source_file/#{new_name}"
    #rename_model "source_record/#{file_name}", "source_record/#{new_name}"
    from_table_name = "source_record_#{file_name.pluralize}"
    if connection.table_exists?(from_table_name)
      migration_template "migrations/rename_source_record.rb.erb", "db/migrate/rename_source_record_#{file_name}_to_#{new_name}.rb"
    end
  end

  private

  def connection
    ActiveRecord::Base.connection
  end

  def rename_model(from_name, to_name)
    from_path = Rails.root.join('app/models', from_name)
    to_path = Rails.root.join('app/models', to_name)
    if File.exist? to_path
      puts "There already exists a model at the path #{to_path}, skipping model rename for #{from_path}"
      FileUtils.mv from_path, to_path
      gsub_file to_path, from_name.classify, to_name.classify
    end
  end

  def new_name
    @new_name = options.new_name.underscore.singularize
  end

  def new_class_name
    new_name.classify
  end
end
