require 'generators/common'

module Batman
  module Generators
    class AppGenerator < ::Rails::Generators::Base
      include Common
      requires_app_name

      desc "This generator installs Batman.js with a default folder layout"

      class_option :skip_git, :type => :boolean, :aliases => "-G", :default => false,
                              :desc => "Skip Git ignores and keeps"

      def setup_rails
        with_app_name do
          template "rails/controller.rb", "app/controllers/#{app_name}_controller.rb"
          template "rails/layout.html", "app/views/layouts/#{app_name}.html.erb"
          template "rails/index.html", "app/views/#{app_name}/index.html.erb"

          inject_into_file "config/routes.rb", :after => "#{js_application_name}::Application.routes.draw do\n"  do
            route_catchall
          end

          remove_file 'public/index.html'
        end
      end

      def create_app
        with_app_name do
          template "batman/batman_app.coffee", "#{app_path}/#{application_name}.js.coffee"
        end
      end

      def create_directories
        %w(models views controllers html lib).each do |dir|
          empty_directory "#{app_path}/#{dir}"
          create_file "#{app_path}/#{dir}/.gitkeep" unless options[:skip_git]
        end
      end

      def inject_batman
        with_app_name do
          application_file = File.join(app_path, "#{application_name}.js.coffee")

          prepend_file application_file do
            batman_requires
          end

        end
      end

      private

      def route_catchall
# \n  match ":controller(/:action(/:id))", to: "#{app_name}\#index", :constraints => { :format => 'html' }\n
<<-CODE
\n  match "(/*redirect_path)", to: "#{app_name}\#index", :constraints => { :format => 'html' }\n
CODE
      end

      def batman_requires
<<-CODE
#= require batman/es5-shim

#= require batman/batman
#= require batman/batman.rails

#= require jquery
#= require batman/batman.jquery

#= require_self

#= require_tree ./controllers
#= require_tree ./models
#= require_tree ./views
#= require_tree ./lib\n
CODE
      end
    end
  end
end
