// ==UserScript==
// @name         gitea-add-swagger-button
// @namespace    https://integratielaag.nl/
// @version      0.1.1
// @description  Creates a button in Gitea to view Swagger
// @author       bboterm
// @match        https://git.integratielaag.nl/*.yaml
// @match        https://git.integratielaag.nl/*.json
// @icon         https://www.google.com/s2/favicons?sz=64&domain=gitea.com
// @grant        none
// @updateURL    https://git.integratielaag.nl/HTM/ovpay/raw/branch/develop/src/plugins/gitea-add-swagger-button.user.js
// @downloadURL  https://git.integratielaag.nl/HTM/ovpay/raw/branch/develop/src/plugins/gitea-add-swagger-button.user.js
// ==/UserScript==
// @history      0.1.0 Initial release
// @history      0.1.1 Added support for YAML and JSON files

(function() {
    'use strict';

    // Set the base URL for the Swagger instance
    const swaggerBaseURL = 'https://swagger.integratielaag.nl/?url=';
    // Get the base URL from the current webpage
    const gitBaseURL = window.location.origin;

    // Replace 'parent-class-name' with the class name of the parent div
    const parentClassName = 'file-actions';
    // Replace 'child-class-name' with the class name of the child div
    const childClassName = 'buttons';

    const parentDiv = document.querySelector('div.file-actions');
    if (parentDiv) {
        const childDiv = parentDiv.querySelector('div.buttons');
        if (childDiv) {
            const firstATag = childDiv.querySelector('a');
            if (firstATag) {
                // Get the URL of the raw file
                const hrefValue = firstATag.getAttribute('href');
                // Create a string literal for the new Swagger button
                const swaggerButton = `<a class="ui mini basic button" target="_blank" href="${swaggerBaseURL}${gitBaseURL}/${hrefValue}">Swagger</a>`;
                // Add the Swagger button to the HTML
				childDiv.innerHTML = swaggerButton + childDiv.innerHTML;
            } else {
                console.log('No <a> tag found inside the child div.');
            }
        } else {
            console.log(`Child div with class '${childClassName}' not found.`);
        }
    } else {
        console.log(`Parent div with class '${parentClassName}' not found.`);
    }
})();

