import '../../../literyz-js/extensions.dist.js';

import TabContentService from './tab-content-service.js';


class AContentService extends TabContentService {

    constructor(popupService) {
        super(popupService);

        const a = this;

        a._containerId = "nav-hyperlinks";
        a._optionsCol1 = [
            { id: 1, text: "Show Anchor as HTML", checked: false },
            { id: 4, text: "Resolve Relative URL", checked: false }
        ];
        a._optionsCol2 = [
            { id: 3, text: "Sort By Anchor Text", checked: true },
            { id: 2, text: "Trim Anchor Text", checked: true }
        ];
        a._filtersCol1 = [
            { id: 12, text: "Hide External Links", checked: true },
            { id: 5, text: "Hide Duplicates", checked: true },
            { id: 14, text: "Hide Blank Anchors", checked: true },
            { id: 15, text: "Hide Blank Links", checked: true },
            { id: 11, text: "Hide Fragments", checked: true },
            { id: 13, text: "Hide Mailto/Tel", checked: true },
            { id: 16, text: "Hide Javascript", checked: true }
        ];
        a._filtersCol2 = [
            { id: 6, text: "Show Title", checked: true },
            { id: 7, text: "Show Target", checked: false },
            { id: 8, text: "Show Rel", checked: false },
            { id: 9, text: "Show Type", checked: false },
            { id: 10, text: "Show Count", checked: false }
        ];

    }

    async _retrieveResult() {
        return await this._popupService.GetHyperlinks();
    }

    async _filterResult(items) {
        const a = this;
        const currentUrl = await a._popupService.GetLocation();
        const currentHostname = (new URL(currentUrl)).hostname;

        let result = [];

        for (let i=0; i<items.length; i++) {
            const item = items[i];

            // Hide fragments
            if (a._getCheckBox(11)) {
                if (item.href.startsWith("#")) {
                    continue;
                }
            }

            // Hide Blank Links
            if (a._getCheckBox(15)) {
                if (String.isNullOrWhitespace(item.href)) {
                    continue;
                }
            }

            // Hide mailto/tel
            if (a._getCheckBox(13)) {
                if (item.href.toLowerCase().startsWith("telno:") || item.href.toLowerCase().startsWith("mailto:")) {
                    continue;
                }
            }

            // Hide javascript
            if (a._getCheckBox(16)) {
                if (item.href.toLowerCase().startsWith("javascript:")) {
                    continue;
                }
            }

            const absoluteUrl = new URL(item.href, currentUrl);

            // Hide external links
            if (a._getCheckBox(12)) {
                if (currentHostname != absoluteUrl.hostname) {
                    continue;
                }
            }

            // Show anchor as html
            let text = (a._getCheckBox(1) ? item.innerHTML : item.innerText);

            // Hide Blank Anchors
            if (a._getCheckBox(14)) {
                if (String.isNullOrWhitespace(text)) {
                    continue;
                }
            }

            // Resolve relative url
            const href = (a._getCheckBox(4) ? absoluteUrl.href : item.href);

            // Trim anchor text
            if (a._getCheckBox(2)) {
                text = text.trim();
            }

            // Search term
            if (!String.isNullOrWhitespace(a._textBox1.value)) {
                if (a._getComboBox(1) == "href") {
                    if (!href.toLowerCase().includes(a._textBox1.value.toLowerCase())) {
                        continue;
                    }
                } else {
                    if (!text.toLowerCase().includes(a._textBox1.value.toLowerCase())) {
                        continue;
                    }
                }
            }

            result.push({
                text: text,
                href: href,
                title: (a._getCheckBox(6) ? item.title : ""),
                target: (a._getCheckBox(7) ? item.target : ""),
                rel: (a._getCheckBox(8) ? item.rel : ""),
                type: (a._getCheckBox(9) ? item.type : ""),
                occurrence: ""
              });
        }

        // Show occurrence
        if (a._getCheckBox(10)) {
            // Calc occurrences, store in cache
            let occurrenceCache = [];
            for (let i=0; i<result.length; i++) {
                const occurrence = result.filter(item => JSON.stringify(item) === JSON.stringify(result[i])).length;

                occurrenceCache.push(occurrence);
            }

            // Update result with occurrence
            for (let i=0; i<result.length; i++) {
                result[i].occurrence = occurrenceCache[i];
            }
        }

        // Hide duplicates
        if (a._getCheckBox(5)) {
            result = result.distinct();
        }

        // Sort by anchor text
        if (a._getCheckBox(3)) {
            result = result.orderBy("text");
        }

        return result;
    }

    _renderTable(results) {
        const a = this;
        const table = a._generateTable();

        a._setHtml(a._panel3, table);

        const thead = a._panel3.querySelectorAll("thead")[0];
        const tbody = a._panel3.querySelectorAll("tbody")[0];

        // Write thead
        thead.innerHTML = "<tr>" + a.#generateTableHeader() + "</tr>";

        // Write tbody
        for (let i=0; i<results.length; i++) {
            const item = results[i];

            let row = [ item.text, item.href ];

            if (a._getCheckBox(6)) {
                row.push(item.title);
            }

            if (a._getCheckBox(7)) {
                row.push(item.target);
            }

            if (a._getCheckBox(8)) {
                row.push(item.rel);
            }

            if (a._getCheckBox(9)) {
                row.push(item.type);
            }

            if (a._getCheckBox(10)) {
                row.push(item.occurrence);
            }

            tbody.innerHTML += a.GenerateRow(row);
        }
    }

    _renderCSV(results) {
        const a = this;
        const textarea = a._generateTextarea();

        a._setHtml(a._panel3, textarea);

        const tbody = a._panel3.querySelectorAll("textarea")[0];

        for (let i=0; i<results.length; i++) {
            const item = results[i];

            let row = [ item.text, item.href ];

            if (a._getCheckBox(6)) {
                row.push(item.title);
            }

            if (a._getCheckBox(7)) {
                row.push(item.target);
            }

            if (a._getCheckBox(8)) {
                row.push(item.rel);
            }

            if (a._getCheckBox(9)) {
                row.push(item.type);
            }

            if (a._getCheckBox(10)) {
                row.push(item.occurrence);
            }

            tbody.value += a.GenerateCSVLine("\t", row);
            tbody.value += "\n";
        }
    }

    _renderLinks(results) {
        const a = this;
        const textarea = a._generateTextarea();

        a._setHtml(a._panel3, textarea);

        const tbody = a._panel3.querySelectorAll("textarea")[0];

        for (let i=0; i<results.length; i++) {
            const item = results[i];

            tbody.value += a.GenerateCSVLine("\t", [ item.href ]);
            tbody.value += "\n";
        }
    }

    #generateTableHeader() {
        const a = this;

        const columns1 = [
            "Anchor Text",
            "Address"
        ];
        const columns2 = [
            { id: 6, name: "Title" },
            { id: 7, name:  "Target" },
            { id: 8, name:  "Rel" },
            { id: 9, name:  "Type" },
            { id: 10, name:  "Count" }
        ];

        return a._generateTableHeader(columns1, columns2);
    }

}


export default AContentService;