# frozen_string_literal: true

module Matterhorn
  class Web < Matterhorn::Roda
    route 'queues', 'api/v1' do |r|
      r.is do
        Matterhorn::API::Response.new(queues: Matterhorn::Models::Queue.all).to_json
      end

      r.get String do |platform|
        break unless PROJECTS[:platforms].key?(platform.to_sym)

        queues = Matterhorn::Models::Queue.find_by_platform(platform)
        jobs = {}
        queues.each { |_id, queue| jobs.merge!(queue.jobs) }
        Matterhorn::API::Response.new(queues: queues, jobs: jobs).to_json
      end
    end

    route 'queue', 'api/v1' do |r|
      r.on /((?:\w|-)+\/(?:\w|-)+)/i do |project|
        break if PROJECTS[:projects][project].nil?

        r.post 'pause' do
          r.halt 401 unless queue_manager?(project) do |entry|
            entry.operation_name = 'PauseQueue'
            entry.handler = "#{self.class}#route"
          end
          queue = Matterhorn::Models::Queue.new(project)
          queue.pause!
          response = Matterhorn::API::Response.new(queue: queue)
          Matterhorn::FayeMessage.send(channel: queue.channel, data: response)
          response.to_json
        end

        r.post 'unpause' do
          r.halt 401 unless queue_manager?(project) do |entry|
            entry.operation_name = 'UnpauseQueue'
            entry.handler = "#{self.class}#route"
          end
          queue = Matterhorn::Models::Queue.new(project)
          queue.unpause!
          response = Matterhorn::API::Response.new(queue: queue)
          Matterhorn::FayeMessage.send(channel: queue.channel, data: response)
          response.to_json
        end

        r.get do
          queue = Matterhorn::Models::Queue.new(project)
          Matterhorn::API::Response.new(queue: queue, jobs: queue.jobs).to_json
        end
      end
    end
  end
end
