module Qeweney::RoutingMethods

def default

def default
  yield
  throw :stop, :found
end

def enter_route

def enter_route
  @path_parts_idx += 1
end

def is(route = '/', &block)

def is(route = '/', &block)
  return unless @path_parts[@path_parts_idx] == route && @path_parts_idx >= @path_parts.size
  route_found(&block)
end

def leave_route

def leave_route
  @path_parts_idx -= 1
end

def on(route = nil, &block)

def on(route = nil, &block)
  if route
    return unless @path_parts[@path_parts_idx] == route
  end
  enter_route
  route_found(&block)
  leave_route
end

def on_accept(accept, &block)

def on_accept(accept, &block)
  if accept.is_a?(Regexp)
    return unless headers['accept'] =~ accept
  else
    return unless headers['accept'] == accept
  end
  route_found(&block)
end

def on_get(route = nil, &block)

def on_get(route = nil, &block)
  return unless method == 'get'
  on(route, &block)
end

def on_host(route, &block)

def on_host(route, &block)
  return unless host == route
  route_found(&block)
end

def on_options(route = nil, &block)

def on_options(route = nil, &block)
  return unless method == 'options'
  on(route, &block)
end

def on_plain_http(route, &block)

def on_plain_http(route, &block)
  return unless scheme == 'http'
  route_found(&block)
end

def on_post(route = nil, &block)

def on_post(route = nil, &block)
  return unless method == 'post'
  on(route, &block)
end

def on_query_param(key)

def on_query_param(key)
  value = query[key]
  return unless value
  route_found { yield value }
end

def on_root(&block)

def on_root(&block)
  return unless @path_parts_idx > @path_parts.size - 1
  route_found(&block)
end

def on_upgrade(protocol, &block)

def on_upgrade(protocol, &block)
  return unless upgrade_protocol == protocol
  route_found(&block)
end

def on_upgrade(protocol, &block)

def on_upgrade(protocol, &block)
  return unless upgrade_protocol == protocol
  route_found(&block)
end

def on_websocket_upgrade(&block)

def on_websocket_upgrade(&block)
  on_upgrade('websocket', &block)
end

def route(&block)

def route(&block)
  (@path_parts ||= path.split('/'))[@path_parts_idx ||= 1]
  res = catch(:stop) { yield self }
  return if res == :found
  respond(nil, ':status' => 404)
end

def route_found(&block)

def route_found(&block)
  catch(:stop, &block)
  throw :stop, headers_sent? ? :found : nil
end

def route_part

def route_part
  @path_parts[@path_parts_idx]
end

def route_relative_path

def route_relative_path
  @path_parts[@path_parts_idx..-1].join('/')
end

def stop_routing

def stop_routing
  throw :stop, :found
end