# Inline hack to fix missing .origin from some browsers (such as IE < 11)
unless window.location.origin
  port_part = if window.location.port then ":" + window.location.port else ""
  window.location.origin = window.location.protocol + "//" + window.location.hostname + port_part

# Extends SwaggerUi to load 3scale extensions
swagger_ui_load = SwaggerUi::load
class ThreeScaleSwaggerUi
  constructor: (swagger_ui_load) ->
    @swagger_ui_load = swagger_ui_load

  load: (account_type)->
    ThreeScaleAutoComplete.init(account_type || "buyer")
    swagger_ui_load.apply @swagger_ui_load

SwaggerUi.prototype.load = (account_type)->
  new ThreeScaleSwaggerUi(this).load(account_type)

# Extends SwaggerResource to add notifications
# A notification is generated by the active-docs to swagger 1.2 translator
swagger_add_api_declaration = SwaggerResource::addApiDeclaration
class ThreeScaleResource
  constructor: (swagger_api_declaration) ->
    @swagger_api_declaration = swagger_api_declaration

  # A notification is generated by the translator
  addApiDeclaration: (response) ->
    @swagger_api_declaration['__notifications'] = response.__notifications
    swagger_add_api_declaration.apply @swagger_api_declaration, [response]

SwaggerResource.prototype.addApiDeclaration = (response) ->
  new ThreeScaleResource(this).addApiDeclaration(response)

# Extends SwaggerHttp to send requests to api_docs proxy
swagger_execute = SwaggerHttp::execute
class ThreeScaleHttp

  NO_CACHE_HEADERS = { "Cache-Control": "no-cache"  }

  constructor: (swagger_http) ->
    @swagger_http = swagger_http

  execute: (obj) ->
    <% if Rails.configuration.three_scale.active_docs_proxy_disabled %>
    if @originHttps() then obj.url = @forceHttpsProtocol obj.url
    <% end %>
    @createLinkElement obj.url
    obj.useJQuery = true
    obj.originalUrl = obj.url

    if not @sameOrigin()
      if _.isUndefined obj.method
        obj.method = obj.type || "POST" # fallback to POST

      patt = new RegExp(":\/\/.*\.execute-api\..*amazonaws\.com")
      if patt.test(obj.originalUrl) || ThreeScaleHttp.beta
        obj.url = 'https://apidocsresty.3sca.net/api_docs/proxy'
      else
        obj.url = @locationOrigin() + '/api_docs/proxy'

      obj.url += '?_=' + (new Date).getTime() # cache buster

      $.extend obj.headers, NO_CACHE_HEADERS, @apiDocsHeaders(obj)

    result = swagger_execute.apply @swagger_http, [obj]

    # restore url for display purposes
    if not @sameOrigin()
      result.url = obj.url = obj.originalUrl

    result

  apiDocsHeaders: (obj) -> {
    'X-Apidocs-Method': obj.method,
    'X-Apidocs-Path'  : @apiDocsPath(),
    'X-Apidocs-Url'   : @desiredOrigin(),
    'X-Apidocs-Query' : @linkElement.search.replace("?", "")
  }

  # we can't use .pathname as it does not add / in IE so this awesome code is to make IE happy
  apiDocsPath: ->
    if @linkElement.pathname.indexOf("/") isnt 0
      "/#{@linkElement.pathname}"
    else
      @linkElement.pathname

  originHttps: ->
    window.top.location.protocol == 'https:'

  forceHttpsProtocol: (url) ->
    url.replace(/^http:\/\//i, 'https://')

  locationOrigin: ->
    window.top.location.origin

  createLinkElement: (url) ->
    @linkElement = window.document.createElement "a"
    @linkElement.href = url
    @linkElement

  sameOrigin: ->
    <% if Rails.configuration.three_scale.active_docs_proxy_disabled %>
      true
    <% else %>
      @desiredOrigin() == @locationOrigin()
    <% end %>

  desiredOrigin: ->
     # This is to make IE happy.
     # https://connect.microsoft.com/IE/feedback/details/817343/ie11-scripting-value-of-htmlanchorelement-host-differs-between-script-created-link-and-link-from-document
    if @linkElement.port is "443" and @linkElement.protocol is "https:"
      portPart = ""
    else
      portPart = if @linkElement.port is "" then "" else ":" + @linkElement.port
    @linkElement.protocol + "//" + @linkElement.hostname + portPart

window.ThreeScaleHttp = ThreeScaleHttp
SwaggerHttp.prototype.execute = (obj) ->
  new ThreeScaleHttp(this).execute(obj)

