require 'fileutils'
require 'rails/generators/active_record'
require 'dunlop/generators'
class Dunlop::WorkflowStepGenerator < Rails::Generators::NamedBase
  include Rails::Generators::Migration
  include Dunlop::Generators::GeneratorHelpers
  source_root File.expand_path('../templates', __FILE__)
  class_option :scenarios, type: :array, default: []
  class_option :attributes, type: :array, default: []

  def setup_scenarios
    unless scenarios.any?
      abort "you have not specified the scenarios for the workflow step. Define using\n  --scenarios=#{WorkflowInstance.scenario_names.join(' ')}\nor\n  --scenarios=all"
    end
    scenarios.each do |scenario|
      @scenario = scenario
      #template "workflow_step_model.rb.erb", "app/models/#{workflow_step}/#{file_name}.rb"
      #template "workflow_step_collection.rb.erb", "app/models/#{workflow_step}/#{file_name}/collection.rb"

      template "scenario_model.rb.erb", "app/models/#{file_name}/#{scenario}.rb"
      template "scenario_collection_model.rb.erb", "app/models/#{file_name}/#{scenario}/collection.rb"
      template "scenario_controller.rb.erb", "app/controllers/#{file_name}/#{scenario.pluralize}_controller.rb"
      template "feature_spec.rb.erb", "spec/features/workflow_steps/#{file_name}_spec.rb"
    end
    if behavior == :revoke and (WorkflowInstance.scenario_names - workflow_step.map(&:to_sym)).any?
      abort "There are still scenarios associated with the workflow step, so the base models will remain"
    end
  end

  def add_creation_migration
    migration_template "migration.rb.erb", "db/migrate/create_#{file_name.pluralize}.rb"
  end

  def create_controller
    template "workflow_step_controller.rb.erb", "app/controllers/#{file_name.pluralize}_controller.rb"
    if behavior == :revoke
      FileUtils.rm_rf Rails.root.join("app/controllers/#{file_name.pluralize}/")
    end
  end

  def create_model
    template "workflow_step_model.rb.erb", "app/models/#{file_name}.rb"
    if behavior == :revoke
      FileUtils.rm_rf Rails.root.join("app/models/#{file_name}/")
      FileUtils.rm_rf Rails.root.join("app/models/#{file_name}.rb")
    end
  end

  def generate_views
    template "translations.yml.erb", "config/locales/workflow_step-#{file_name}.yml"
    directory "views/general_views", "app/views/#{file_name.pluralize}"
    template "views/collection_form.html.slim.erb", "app/views/#{file_name.pluralize}/_collection_form.html.slim"

    add_to_symbol_list "app/models/workflow_instance.rb", 'setup_possible_workflow_steps', file_name
  end

  def generate_spec_helpers
    template "factories.rb.erb", "spec/factories/#{file_name}.rb"
  end

  private

  def scenario
    @scenario
  end

  def scenarios
    options.scenarios == ['all'] ? WorkflowInstance.scenario_names.map(&:to_s) : options.scenarios
  end
end
