module Devops
  module API3
    module Routes
      module ImageRoutes

        def self.registered(app)

          app.define_policy :read_images, "Read images"
          app.define_policy :create_images, "Create image"
          app.define_policy :delete_images, "Delete image"

          app.get_with_headers "/images" do
            check_policy(:read_images)
            json Devops::API3::Handler::Image.new(request).images.map(&:to_hash)
          end

          app.post_with_headers "/image" do
            check_policy(:create_images)
            image = Devops::API3::Handler::Image.new(request).create_image()
            create_response "Created", {id: image.id}, 201
          end

          hash = {}
          hash["GET"] = lambda { |id|
            check_policy(:read_images)
            json Devops::API3::Handler::Image.new(request).image(id).to_hash
          }

          hash["PUT"] = lambda {|id|
            check_policy(:create_images)
            image = Devops::API3::Handler::Image.new(request).update_image(id)
            create_response("Image '#{id}' has been updated", {image: image.to_hash})
          }

          hash["DELETE"] = lambda {|id|
            check_policy(:delete_images)
            Devops::API3::Handler::Image.new(request).delete_image(id)
            create_response("Image '#{id}' has been removed", {id: id})
          }

          app.multi_routes "/image/:id", hash

          puts "Image routes initialized"
        end

      end
    end
  end
end
