<!DOCTYPE html>
<html>
  <head>
    <title>Swagger Concrete</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
  </head>
  <body>
    <div id="swagger-ui"></div>
    <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
    <script>
    window.onload = function() {
      var token = '';

      // Override functionality of Authorize and Logout to reload the endpoints
      // later on. Here, we just store/ delete the token.
      // Per default, the endpoints are not loaded after authorization
      const MyWrapAuthPlugin = function(system) {
        return {
          statePlugins: {
            auth: {
              wrapActions: {
                authorize: (oriAction) => (obj) => {
                  if ('Token' in obj && 'value' in obj['Token']){
                    token = obj['Token']['value']
                    system.specActions.download()
                  }
                  return oriAction(obj)
                },
                logout: (oriAction) => (obj) => {
                  token = ''
                  system.specActions.download()
                  return oriAction(obj)
                }
              }
            }
          }
        }
      }

      const ui = SwaggerUIBundle({
              url: "{% url schema_url spec_format='json' %}",
              dom_id: '#swagger-ui',
              presets: [
                SwaggerUIBundle.presets.apis,
                SwaggerUIBundle.SwaggerUIStandalonePreset
              ],
              // use the plugin above
              plugins: [MyWrapAuthPlugin],
              layout: "BaseLayout",
              // Intercept the response in case the user entered an invalid
              // token, so that he or she will be informed.
              responseInterceptor: (res) => {
                if (res.status === 403) {
                  console.log(res)
                  res.statusText = 'Forbidden: Invalid Token (refresh to try again)'
                }
                return res;
              },
              // Intercept requests, to make sure that the token is set as
              // auth header after authorization is clicked.
              requestInterceptor: (request) => {
                if(token != ''){
                  if(token.includes("Token ")){
                    request.headers['Authorization'] = token;
                  }
                  else{
                    request.headers['Authorization'] = "Token " + token;
                  }

                }
                request.headers['X-CSRFToken'] = "{{ csrf_token }}"
                return request;
              }
            })
    }
    </script>
  </body>
</html>
