require "commands/image"
require "db/mongo/models/image"
require "app/api3/parsers/image"
require_relative "request_handler"

module Devops
  module API3
    module Handler
      class Image < RequestHandler

        set_parser Devops::API3::Parser::ImageParser

        def images
          provider = parser.images
          if provider
            Devops::Model::Image.where(provider: provider)
          else
            Devops::Model::Image.all
          end
        end

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

        def create_image
          image = parser.image
          image.save!
          DevopsLogger.logger.info "Image '#{image.id}' has been created"
          image
        rescue Mongoid::Errors::Validations => e
          raise Devops::Exception::ValidationError.create_from_db_exception(e)
        end

        def update_image id
          image = image(id)
          obj = parser.image
          image.update_attributes! obj.to_hash_update
          DevopsLogger.logger.info "Image '#{image.id}' has been updated"
          image
        rescue Mongoid::Errors::Validations => e
          raise Devops::Exception::ValidationError.create_from_db_exception(e)
        end

        def delete_image id
          projects = Devops::Model::Project.find_by('environments.image' => id)
          ar = []
          projects.each do |p|
            ar += p.environments.select{|e| e.respond_to?(:image)}.select{|e| e.image == id}.map{|e| "#{p.id}.#{e.id}"}
          end
          raise DependencyError.new "Deleting is forbidden: Image is used in #{ar.join(", ")}"
        rescue Mongoid::Errors::DocumentNotFound
          image(id).delete
          DevopsLogger.logger.info "Image '#{id}' has been deleted"
        end

      end
    end
  end
end

