require "db/mongo/models/key"
require "fileutils"
require "app/api3/parsers/key"
require_relative "request_handler"

module Devops
  module API3
    module Handler
      class Key < RequestHandler

        set_parser Devops::API3::Parser::KeyParser

        def keys
          Devops::Model::Key.all
        end

        def key id
          Devops::Model::Key.find(id)
        rescue Mongoid::Errors::DocumentNotFound
          raise Devops::Exception::RecordNotFound.new("Key with id '#{id}' not found")
        end

        def create(keys_dir)
          body = parser.create
          fname = body["file_name"]
          file_name = File.join(keys_dir, fname)
          raise Devops::Exception::ValidationError.new("File '#{fname}' already exist") if File.exists?(file_name)
          File.open(file_name, "w") do |f|
            f.write(body["content"])
            f.chmod(0400)
          end

          key = Devops::Model::Key.create!({"path" => file_name, "id" => body["key_name"]})
          DevopsLogger.logger.info "Key '#{key.id}' has been created"
          key
        end

        def delete key_id
          k = key(key_id)
          servers = []
          Devops::Model::Server.where(key: k.id).each do |s|
            servers << s.id
          end
          unless servers.empty?
            s_str = servers.join(", ")
            raise DependencyError.new "Deleting is forbidden: Key is used in servers: #{s_str}"
          end
          k.destroy
          DevopsLogger.logger.info "Key '#{k.id}' has been deleted"
        end

      end
    end
  end
end

