require "lib/core_ext/hash"
require "lib/core_ext/nil_class"
require "lib/core_ext/string"

require_relative "devops-loader"
require_relative "devops-application"
require_relative "devops-db"
require_relative "devops-logger"
require_relative "devops-messages"

require "providers/provider.rb"

require "lib/ssh/ssh_utils"

require_relative "../sinatra/methods_with_headers"

require_relative "../applications"
require_relative "devops-routes"

class DevopsService

  class << self

    def init
      Devops::Db.init(Sinatra::Base.environment)
      DevopsLogger.logger = DevopsLogger.create($stdout)

      if DevopsConfig.config[:url_prefix].nil?
        DevopsConfig.config[:url_prefix] = ""
      elsif !DevopsConfig.config[:url_prefix].empty?
        DevopsConfig.config[:url_prefix] = "/" + DevopsConfig.config[:url_prefix] unless DevopsConfig.config[:url_prefix].start_with?("/")
      end
      Devops::Routes.preffix = DevopsConfig.config[:url_prefix]
      Devops::Messages.init

      load_apps
      prepare_apps_and_plugins
      init_apps_and_plugins
      load_routes

      KnifeFactory.init
    end

    def load_apps
      @apps = Devops::Application.applications
    end

    def prepare_apps_and_plugins
      @apps.each(&:prepare)
      Devops::Loader.prepare_plugins
    end

    def init_apps_and_plugins
      @apps.each(&:init)
      Devops::Loader.init_plugins
    end

    def load_routes
      @apps.each(&:routes)
      Devops::Loader.routes
    end

    def debug?
      DevopsConfig.config[:debug]
    end
  end

end
