module Devops
  class DevopsApi3Application < Application

    def prepare
      require "auth/devops_auth"
      require_relative "api3/routes/v3.0"
      require_relative "api3/handlers/provider"
      require_relative "api3/handlers/filter"
      require_relative "api3/handlers/user"
      require_relative "api3/handlers/job_task"
      require_relative "api3/handlers/deploy"
      require_relative "api3/handlers/script"
      require_relative "api3/handlers/chef"
      require_relative "api3/handlers/key"
      require_relative "api3/handlers/server"
      require_relative "api3/handlers/image"
      require_relative "api3/handlers/project"
      require_relative "api3/handlers/stack"
      require_relative "api3/handlers/stack_template"
      require_relative "api3/handlers/roles"
      require_relative "api3/handlers/statistic"
      require_relative "api3/handlers/api-docs"

      require 'lib/stubber'
    end

    def init
      config = DevopsConfig.config
      Devops::Api3.set :devops_home, config[:devops_dir]
      #set :config, config

      Devops::Api3.set :keys_dir, (config[:keys_dir] || File.join(config[:devops_dir], "files/keys"))
      Devops::Api3.set :scripts_dir, (config[:scripts_dir] || File.join(config[:devops_dir], "files/scripts"))
      [:keys_dir, :scripts_dir].each {|key| d = Devops::Api3.settings.send(key); FileUtils.mkdir_p(d) unless File.exists?(d) }
      #mongo = Devops::Api2.settings.mongo
      #mongo.create_root_user
      Devops::Model::User.create_root
      Stubber.stub_providers!(config[:stub_providers])
    end

    def routes
      require_relative "api3/routes/image"
      require_relative "api3/routes/filter"
      require_relative "api3/routes/deploy"
      require_relative "api3/routes/project"
      require_relative "api3/routes/key"
      require_relative "api3/routes/user"
      require_relative "api3/routes/provider"
      require_relative "api3/routes/server"
      require_relative "api3/routes/script"
      require_relative "api3/routes/chef"
      require_relative "api3/routes/stack"
      require_relative "api3/routes/stack_template"
      require_relative "api3/routes/statistic"
      require_relative "api3/routes/job_task"
      require_relative "api3/routes/roles"
      require_relative "api3/routes/api-docs"

      routes = Devops::API3::Routes.constants.collect{|s| Devops::API3::Routes.const_get(s)}.select {|const| const.class == Module}
      routes.each do |r|
        Devops::Api3.register r
      end
      DevopsLogger.logger.debug "Api3 routes policies: #{Devops::Api3.policies.inspect}"
      Routes.route "/v3", Devops::Api3
      #Devops::Api2.routes_list
    end

  end
end

