#!/usr/bin/env ruby

require "rubygems"
require "bundler/setup"
require 'byebug'

root = File.dirname(__FILE__) + '/..'
$:.push root

$stdout = File.open(File::NULL, "w")
require "core/devops-service"
require "core/devops-config"
require "core/devops-routes"
DevopsConfig.read
DevopsService.init
$stdout = STDOUT

class Route
  attr_reader :verb, :human_path
  def initialize(verb, sinatra_route)
    @verb = verb
    @human_path = humanize(sinatra_route.first)
  end

  def humanize(route_regex)
    result = route_regex.to_s.sub!('(?-mix:\A\\', '').sub!('\z)','')
    result.gsub!('([^\/?#]+)', ":param")
    result.gsub!('\/', '/')
    result
  end
end

class AppRoutes
  attr_reader :prefix, :routes
  def initialize(prefix, routes)
    @prefix, @routes = prefix, routes
  end

  def print
    sorted = @routes.sort_by(&:human_path)
    sorted.each do |route|
      puts "#{route.verb} #{@prefix}#{route.human_path}"
    end
    puts "\n\n"
  end
end


collections = Devops::Routes.routes.map do |prefix, app|
  routes = Devops::Api3.routes.map do |verb, sinatra_routes|
    sinatra_routes.map { |r|  Route.new(verb, r) }
  end.flatten
  AppRoutes.new(prefix, routes)
end

# there isn't easy way to get routes by name
apps_order = %w(sidekiq client version backend)

if ARGV.first == 'all'
  apps_to_show = %w(sidekiq client version backend)
elsif ARGV.first
  apps_to_show = [ARGV.first]
else
  apps_to_show = ['backend']
end

apps_to_show.each do |app|
  collections[apps_order.index(app)].print
end


