// We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import "../css/app.scss"

// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import deps with the dep name or local files with a relative path, for example:
//
//     import {Socket} from "phoenix"
//     import socket from "./socket"
//
import "phoenix_html"

window.onload = function () {
    document.getElementById('archiveUrlInput').addEventListener('keydown', function(event) {
        setTimeout(function () { generatePodcastUrl(); }, 100)
    });

    document.getElementById('copiaRss').addEventListener('click', function(event) {
        setTimeout(function () { copyToClipboard(fetchPodcastUrl()); }, 100)
    });
};

function fetchArchiveUrl() {
    return document.getElementById("archiveUrlInput").value.trim();
}

function fetchPodcastUrl() {
    return document.getElementById("podcastUrl").value.trim();
}

function generatePodcastUrl() {
    const archiveUrl = fetchArchiveUrl();
    if (!validateArchiveUrl(archiveUrl)) {
        document.getElementById("podcastUrl").value = "";
        return;
    }

    const url = new URL(archiveUrl);
    const podcastName = url.pathname.split("/").slice(-1).pop();
    const podcastUrl = "https://openpod.abbiamoundominio.org/podcast/" + podcastName;

    document.getElementById("podcastUrl").value = podcastUrl;
}

function validateArchiveUrl(url) {
    try {
        const archiveUrl = new URL(url);

        var urlPattern = new RegExp("(http|https)://archive.org/details/[a-zA-Z0-9\._-]*$")
        if (!urlPattern.test(url) ) {
            throw 'Paste and archive.org url';
        }
    } catch (e) {
        return false;
    }

    return true;
}

function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text);

    }
    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        }
        catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        }
        finally {
            document.body.removeChild(textarea);
        }
    }
}

// archiveUrlInput
// https://archive.org/details/uau-pod
// https://openpod.abbiamoundominio.org/podcast/il-mio-podcast
