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


class ImgContentService extends TabContentService {

    constructor(popupService) {
        super(popupService);

        const a = this;

        a._containerId = "nav-images";
        a._optionsCol1 = [
            { id: 203, text: "Sort By Source URL", checked: true },
            { id: 204, text: "Resolve Relative URL", checked: false }
        ];
        a._optionsCol2 = [
            { id: 202, text: "Trim Alternate Text", checked: true }
        ];
        a._filtersCol1 = [
            { id: 212, text: "Hide External Links", checked: false },
            { id: 205, text: "Hide Duplicates", checked: true },
            { id: 214, text: "Hide Blank Alternate Text", checked: false },
            { id: 215, text: "Hide Blank Source URL", checked: true }
        ];
        a._filtersCol2 = [
            { id: 206, text: "Show Alternative Text", checked: true },
            { id: 207, text: "Show Source Set", checked: false },
            { id: 208, text: "Show Image Map", checked: false },
            { id: 210, text: "Show Count", checked: false }
        ];

    }

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

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

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

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

            // Hide blank alternative text
            if (a._getCheckBox(214)) {
                if (String.isNullOrWhitespace(item.alt)) {
                    continue;
                }
            }

            // Resolve source
            const src = (a._getCheckBox(204) ? absoluteUrl.href : item.src);
            const alt = (a._getCheckBox(202) ? item.alt.trim() : item.alt);

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

            result.push({
                src: src,
                alt: (a._getCheckBox(206) ? alt : ""),
                srcset: (a._getCheckBox(207) ? item.srcset : ""),
                usemap: (a._getCheckBox(208) ? item.usemap : ""),
                occurrence: ""
              });
        }

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

        // Sort by source
        if (a._getCheckBox(203)) {
            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(206)) {
                row.push(item.alt);
            }

            if (a._getCheckBox(207)) {
                row.push(item.srcset);
            }

            if (a._getCheckBox(208)) {
                row.push(item.usemap);
            }

            if (a._getCheckBox(210)) {
                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(206)) {
                row.push(item.alt);
            }

            if (a._getCheckBox(207)) {
                row.push(item.srcset);
            }

            if (a._getCheckBox(208)) {
                row.push(item.usemap);
            }

            if (a._getCheckBox(210)) {
                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: 206, name: "Alternative Text" },
            { id: 207, name:  "Source Set" },
            { id: 208, name:  "Image Map" },
            { id: 210, name:  "Count" }
        ];

        return a._generateTableHeader(columns1, columns2);
    }

}


export default ImgContentService;