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


class ScriptContentService extends TabContentService {

    constructor(popupService) {
        super(popupService);

        const a = this;

        a._containerId = "nav-scripts";
        a._optionsCol1 = [
            { id: 303, text: "Sort By Source URL", checked: true },
            { id: 304, text: "Resolve Relative URL", checked: false }
        ];
        a._optionsCol2 = [
            { id: 302, text: "Trim Alternate Type", checked: true }
        ];
        a._filtersCol1 = [
            { id: 312, text: "Hide External Links", checked: false },
            { id: 305, text: "Hide Duplicates", checked: true },
            { id: 314, text: "Hide Blank Type", checked: false },
            { id: 315, text: "Hide Blank Source URL", checked: true }
        ];
        a._filtersCol2 = [
            { id: 306, text: "Show Type", checked: true },
            { id: 310, text: "Show Count", checked: false }
        ];

    }

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

    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 source
            if (a._getCheckBox(315)) {
                if (String.isNullOrWhitespace(item.src)) {
                    continue;
                }
            }

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

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

            // Hide blank type
            if (a._getCheckBox(314)) {
                if (String.isNullOrWhitespace(item.type)) {
                    continue;
                }
            }

            // Resolve source
            const src = (a._getCheckBox(304) ? absoluteUrl.href : item.src);
            const type = (a._getCheckBox(302) ? item.type.trim() : item.type);

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

            result.push({
                src: src,
                type: (a._getCheckBox(306) ? type : ""),
                occurrence: ""
              });
        }

        // Show occurrence
        if (a._getCheckBox(310)) {
            // 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(305)) {
            result = result.distinct();
        }

        // Sort by source
        if (a._getCheckBox(303)) {
            result = result.orderBy("src");
        }

        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.src ];

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

            if (a._getCheckBox(310)) {
                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.src ];

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

            if (a._getCheckBox(310)) {
                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.src ]);
            tbody.value += "\n";
        }
    }

    #generateTableHeader() {
        const a = this;

        const columns1 = [
            "Source"
        ];
        const columns2 = [
            { id: 306, name: "Type" },
            { id: 310, name:  "Count" }
        ];

        return a._generateTableHeader(columns1, columns2);
    }

}


export default ScriptContentService;