require 'sinatra/base'
require 'core/devops-logger'
require 'core/devops-config'

class DevopsClient < Sinatra::Base

  def initialize
    super()
    @@config = DevopsConfig.config
  end

  configure :production do
    config = DevopsConfig.config
    log_file = File.join(config[:log_dir], "devops-client.access.log")
    logger = DevopsLogger.create(log_file, Logger::INFO)
    use Rack::CommonLogger, logger
    disable :dump_errors
    disable :show_exceptions
    logger.info "Production mode"
  end

  configure :development do
#    config = DevopsConfig.config
#    log_file = File.join(config[:log_dir], "devops-client.log")
    logger = DevopsLogger.create(STDOUT, Logger::DEBUG)
    use Rack::CommonLogger, logger
    disable :raise_errors
#      disable :dump_errors
    set :show_exceptions, :after_handler
    logger.info "Development mode"
    DevopsLogger.level = Logger::DEBUG
  end

=begin
  before do
    env["rack.errors"] =  error_logger
  end
=end

  # Route to download devops client
  get "/devops-client.gem" do
    begin
      send_file @@config[:client_file]
    rescue
      msg = "No file '#{@@config[:client_file]}' found"
      logger.error msg
      return [404, msg]
    end
  end

  # Route to get client documentation
  get "/ru/index.html" do
    file = File.join(@@config[:public_dir], "ru_index.html")
    if File.exist? file
      File.read(file)
    else
      logger.error "File '#{file}' does not exist"
      return [404, "File '/ru/index.html' does not exist"]
    end
  end

end

