require "active_record"
require 'yaml'

namespace :db do
  namespace :jam_ruby do
    raise 'Set RAILS_ENV environment variable' if ENV['RAILS_ENV'].blank?
    db_config       = YAML::load(File.open('config/database.yml'))[ENV['RAILS_ENV']]
    db_config_admin = db_config.merge({'database' => 'postgres', 'schema_search_path' => 'public'})

    desc "Create the database"
    task :create do
      ActiveRecord::Base.establish_connection(db_config_admin)
      ActiveRecord::Base.connection.create_database(db_config["database"])
      puts "#{ENV['RAILS_ENV']} database created."
    end

    desc "Migrate the database"
    task :migrate do
      ActiveRecord::Base.establish_connection(db_config)
      migrate_dir = File.expand_path("../../../../../db/migrate",  __FILE__)
      ActiveRecord::Migrator.migrate(migrate_dir)
      puts "#{ENV['RAILS_ENV']} database migrated."
    end

    desc "Rollback the database"
    task :rollback do
      steps = (ARGV[1] || "1").to_i
      ActiveRecord::Base.establish_connection(db_config)
      migrate_dir = File.expand_path("../../../../../db/migrate",  __FILE__)
      ActiveRecord::Migrator.rollback(migrate_dir, steps)
      puts "#{ENV['RAILS_ENV']} database migrated."
    end

    desc "Drop the database"
    task :drop do
      raise "can not drop production database" if ENV['RAILS_ENV'] == 'production'
      ActiveRecord::Base.establish_connection(db_config_admin)
      ActiveRecord::Base.connection.drop_database(db_config["database"])
      puts "#{ENV['RAILS_ENV']} database deleted."
    end

    desc "Reset the database"
    task :reset => [:drop, :create, :migrate]

    desc 'Create a db/schema.rb file that is portable against any DB supported by AR'
    task :schema do
      ActiveRecord::Base.establish_connection(db_config)
      require 'active_record/schema_dumper'
      filename = "db/schema.rb"
      File.open(filename, "w:utf-8") do |file|
        ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
      end
    end

  end

  namespace :g do
    desc "Generate migration"
    task :migration do
      name = ARGV[1] || raise("Specify name: rake db:g:migration your_migration")
      timestamp = Time.now.strftime("%Y%m%d%H%M%S")
      path = File.expand_path("../../../../../db/migrate/#{timestamp}_#{name}.rb", __FILE__)
      migration_class = name.split("_").map(&:capitalize).join

      File.open(path, 'w') do |file|
        file.write <<-EOF
  class #{migration_class} < ActiveRecord::Migration
    def self.up
    end
    def self.down
    end
  end
        EOF
      end

      puts "Migration #{path} created"
      abort # needed stop other tasks
    end
  end
end