module Scrivito
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      include ::Rails::Generators::Migration

      source_root File.expand_path('../templates', __FILE__)

      def self.next_migration_number(dirname)
        Scrivito::Migration.next_migration_number(current_migration_number(dirname))
      end

      def copy_initializer
        copy_file 'config/initializers/scrivito.rb'
      end

      def copy_obj_and_widget_model
        copy_file 'app/models/obj.rb'
        copy_file 'app/models/widget.rb'
      end

      def copy_cms_controller
        copy_file 'app/controllers/cms_controller.rb'
      end

      def copy_dialog_layout
        copy_file 'app/views/layouts/scrivito_dialog.html.erb'
      end

      def copy_migration
        migration_template 'scrivito/migrate/install_scrivito_migration.rb',
          File.join(Scrivito::Configuration.migration_path, 'install_scrivito_migration.rb')
      end

      def copy_page_files
        copy_file 'app/models/page.rb'
        copy_file 'app/controllers/page_controller.rb'
        copy_file 'app/views/page/details.html.erb'
        copy_file 'app/views/page/index.html.erb'
        copy_file 'app/views/page/thumbnail.html.erb'
      end

      def copy_image_files
        copy_file 'app/models/image.rb'
        copy_file 'app/views/image/details.html.erb'
      end

      def copy_download_files
        copy_file 'app/models/download.rb'
        copy_file 'app/views/download/details.html.erb'
      end

      def copy_headline_widget_files
        copy_file 'app/models/headline_widget.rb'
        copy_file 'app/views/headline_widget/show.html.erb'
        copy_file 'app/views/headline_widget/thumbnail.html.erb'
      end

      def copy_text_widget_files
        copy_file 'app/models/text_widget.rb'
        copy_file 'app/views/text_widget/show.html.erb'
        copy_file 'app/views/text_widget/thumbnail.html.erb'
      end

      def copy_image_widget_files
        copy_file 'app/models/image_widget.rb'
        copy_file 'app/views/image_widget/show.html.erb'
        copy_file 'app/views/image_widget/thumbnail.html.erb'
      end

      def append_scrivito_routes
        log :route, "Appending Scrivito routes"
        definition = "\n"\
          "  # Default Scrivito routes. Adapt them to change the routing of CMS objects.\n"\
          "  # See the documentation of 'scrivito_route' for a detailed description.\n"\
          "  scrivito_route '/', using: 'homepage'\n"\
          "  scrivito_route '(/)(*slug-):id', using: 'slug_id'\n"\
          "  scrivito_route '/*permalink', using: 'permalink', format: false\n"\

        inject_into_file 'config/routes.rb', definition, before: /^\s*end\s*\z/, verbose: false
      end
    end
  end
end