"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const UpdateChanges_1 = require("../common/UpdateChanges");
const util_1 = require("../common/util");
const import_helper_js_1 = require("../common/import-helper.js");
const version = '13.0.0';
exports.default = () => (host, context) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    context.logger.info(`Applying migration for Ignite UI for Angular to version ${version}`);
    const { HtmlParser } = yield (0, import_helper_js_1.nativeImport)('@angular/compiler');
    const update = new UpdateChanges_1.UpdateChanges(__dirname, host, context);
    const changes = new Map();
    const tsFiles = update.tsFiles;
    const SERVICES = ['IgxCsvExporterService', 'IgxExcelExporterService'];
    const TAGS = ['igx-grid', 'igx-tree-grid', 'igx-hierarchical-grid', 'igx-row-island'];
    const toolbarProp = ['[showToolbar]', 'showToolbar', '[toolbarTitle]', 'toolbarTitle',
        '[columnHiding]', 'columnHiding', '[columnHidingTitle]', 'columnHidingTitle', '[hiddenColumnsText]', 'hiddenColumnsText',
        '[columnPinning]', 'columnPinning', '[columnPinningTitle]', 'columnPinningTitle', '[pinnedColumnsText]', 'pinnedColumnsText',
        '[exportExcel]', 'exportExcel', '[exportExcelText]', 'exportExcelText',
        '[exportCsv]', 'exportCsv', '[exportCsvText]', 'exportCsvText', '[exportText]', 'exportText'];
    const actionsLeft = ['igx-grid-toolbar-advanced-filtering'];
    const moduleTsFiles = tsFiles.filter(x => x.endsWith('.module.ts'));
    for (const path of moduleTsFiles) {
        let content = (_a = host.read(path)) === null || _a === void 0 ? void 0 : _a.toString();
        const servicesInFile = [];
        SERVICES.forEach(service => {
            if (content.indexOf(service) > -1) {
                servicesInFile.push(service);
            }
        });
        if (servicesInFile.length > 0) {
            let newLine = '\n';
            if (content.indexOf('\r\n') > -1) {
                newLine = '\r\n';
            }
            const comment = '// ' + servicesInFile.join(' and ') + ' no longer need to be manually provided and can be safely removed.' + newLine;
            content = comment + content;
            host.overwrite(path, content);
        }
    }
    const applyChanges = () => {
        var _a;
        for (const [path, change] of changes.entries()) {
            let buffer = (_a = host.read(path)) === null || _a === void 0 ? void 0 : _a.toString();
            change.sort((c, c1) => c.position - c1.position)
                .reverse()
                .forEach(c => buffer = c.apply(buffer));
            host.overwrite(path, buffer);
        }
    };
    const addChange = (path, change) => {
        if (changes.has(path)) {
            changes.get(path).push(change);
        }
        else {
            changes.set(path, [change]);
        }
    };
    const buildToolbar = (node, attributes) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
        let result = '';
        const toolbar = (0, util_1.findElementNodes)(node, ['igx-grid-toolbar'])[0];
        result += `\n<igx-grid-toolbar`;
        const showToolbar = !toolbar || ((_a = attributes['showToolbar']) === null || _a === void 0 ? void 0 : _a.value) ? attributes['showToolbar'] : (0, util_1.getAttribute)(toolbar, ['*ngIf', '[*gIf]'])[0];
        if (showToolbar && showToolbar.value) {
            result += ` *ngIf="${showToolbar.value}"`;
        }
        result += '>';
        const toolbarTitle = !!toolbar ? (0, util_1.findElementNodes)([toolbar], ['igx-grid-toolbar-title'])[0] : null;
        const title = !toolbarTitle || ((_b = attributes['toolbarTitle']) === null || _b === void 0 ? void 0 : _b.value) ? attributes['toolbarTitle'] : (toolbarTitle.children)[0];
        if (title && title.value) {
            result += `\n<igx-grid-toolbar-title>${title.value}</igx-grid-toolbar-title>`;
        }
        // has actions
        const hasHiding = Object.keys(attributes).filter(x => x.toLowerCase().includes('hid')).length > 0 || !!(toolbar && (0, util_1.findElementNodes)([toolbar], ['igx-grid-toolbar-hiding'])[0]);
        const hasPinning = Object.keys(attributes).filter(x => x.toLowerCase().includes('pin')).length > 0 || !!(toolbar && (0, util_1.findElementNodes)([toolbar], ['igx-grid-toolbar-pinning'])[0]);
        const hasExporting = Object.keys(attributes).filter(x => x.toLowerCase().includes('export')).length > 0 || !!(toolbar && (0, util_1.findElementNodes)([toolbar], ['igx-grid-toolbar-exporter'])[0]);
        const hasActions = hasHiding || hasPinning || hasExporting;
        if (hasActions) {
            result += '\n<igx-grid-toolbar-actions>';
        }
        const hiding = !!toolbar ? (0, util_1.findElementNodes)([toolbar], ['igx-grid-toolbar-hiding'])[0] : null;
        const showHiding = !hiding || ((_c = attributes['columnHiding']) === null || _c === void 0 ? void 0 : _c.value) ? attributes['columnHiding'] : (0, util_1.getAttribute)(hiding, ['*ngIf', '[*ngIf]'])[0];
        if (hasHiding) {
            result += `\n<igx-grid-toolbar-hiding`;
        }
        if (showHiding && showHiding.value) {
            result += `${showHiding.value !== "'true'" ? ` *ngIf="${showHiding.value}"` : ''}`;
        }
        const hidingTitle = !hiding || ((_d = attributes['columnHidingTitle']) === null || _d === void 0 ? void 0 : _d.value) ? attributes['columnHidingTitle'] : (0, util_1.getAttribute)(hiding, ['title', '[title]'])[0];
        if (hidingTitle && hidingTitle.value) {
            result += ` title="${hidingTitle.value}"`;
        }
        let buttonText = !hiding || ((_e = attributes['hiddenColumnsText']) === null || _e === void 0 ? void 0 : _e.value) ? attributes['hiddenColumnsText'] : (0, util_1.getAttribute)(hiding, ['buttonText', '[buttonText]'])[0];
        if (buttonText && buttonText.value) {
            result += ` buttonText="${buttonText.value}"`;
        }
        if (hasHiding) {
            result += '></igx-grid-toolbar-hiding>';
        }
        const pinning = !!toolbar ? (0, util_1.findElementNodes)([toolbar], ['igx-grid-toolbar-pinning'])[0] : null;
        const showPinning = !pinning || ((_f = attributes['columnPinning']) === null || _f === void 0 ? void 0 : _f.value) ? attributes['columnPinning'] : (0, util_1.getAttribute)(pinning, ['*ngIf', '[*ngIf]'])[0];
        if (hasPinning) {
            result += `\n<igx-grid-toolbar-pinning`;
        }
        if (showPinning && showPinning.value) {
            result += `${showPinning.value !== "'true'" ? ` *ngIf="${showPinning.value}"` : ''}`;
        }
        const pinningTitle = !pinning || ((_g = attributes['columnPinningTitle']) === null || _g === void 0 ? void 0 : _g.value) ? attributes['columnPinningTitle'] : (0, util_1.getAttribute)(pinning, ['title', '[title]'])[0];
        if (pinningTitle && pinningTitle.value) {
            result += ` title="${pinningTitle.value}"`;
        }
        buttonText = !pinning || ((_h = attributes['pinnedColumnsText']) === null || _h === void 0 ? void 0 : _h.value) ? attributes['pinnedColumnsText'] : (0, util_1.getAttribute)(pinning, ['buttonText', '[buttonText]'])[0];
        if (buttonText && buttonText.value) {
            result += ` buttonText="${buttonText.value}"`;
        }
        if (hasPinning) {
            result += '></igx-grid-toolbar-pinning>';
        }
        const exporting = !!toolbar ? (0, util_1.findElementNodes)([toolbar], ['igx-grid-toolbar-exporter'])[0] : null;
        const showExcelExporter = !exporting || ((_j = attributes['exportExcel']) === null || _j === void 0 ? void 0 : _j.value) ? attributes['exportExcel'] : (0, util_1.getAttribute)(exporting, ['exportExcel', '[exportExcel]'])[0];
        const showCsvExporter = !exporting || ((_k = attributes['exportCsv']) === null || _k === void 0 ? void 0 : _k.value) ? attributes['exportCsv'] : (0, util_1.getAttribute)(exporting, ['exportCSV', '[exportCSV]'])[0];
        if (hasExporting) {
            result += `\n<igx-grid-toolbar-exporter`;
        }
        if (showExcelExporter && showExcelExporter.value) {
            result += ` exportExcel="${showExcelExporter.value}"`;
        }
        if (showCsvExporter && showCsvExporter.value) {
            result += ` exportCSV="${showCsvExporter.value}"`;
        }
        if (hasExporting) {
            result += '>';
        }
        const excelTitle = !exporting || ((_l = attributes['exportExcelText']) === null || _l === void 0 ? void 0 : _l.value) ? attributes['exportExcelText'] : getExportText(exporting, 'excelText');
        if (excelTitle && excelTitle.value) {
            result += excelTitle.template ? '\n' + excelTitle.value : `\n<span excelText>${excelTitle.value}</span>`;
        }
        const csvTitle = !exporting || ((_m = attributes['exportCsvText']) === null || _m === void 0 ? void 0 : _m.value) ? attributes['exportCsvText'] : getExportText(exporting, 'csvText');
        if (csvTitle && csvTitle.value) {
            result += csvTitle.template ? '\n' + csvTitle.value : `\n<span csvText>${csvTitle.value}</span>`;
        }
        const exportTitle = !exporting || ((_o = attributes['exportText']) === null || _o === void 0 ? void 0 : _o.value) ? attributes['exportText'] : getExportText(exporting, 'text');
        if (exportTitle && exportTitle.value) {
            result += '\n' + exportTitle.value;
        }
        if (hasExporting) {
            result += '\n</igx-grid-toolbar-exporter>';
        }
        //add any actions left
        if (toolbar) {
            const actions = (0, util_1.findElementNodes)([toolbar], actionsLeft);
            actions.forEach(action => {
                const { startTag, file, endTag } = (0, util_1.getSourceOffset)(action);
                const text = file.content.substring(startTag.start, endTag.end);
                result += '\n' + text;
            });
        }
        if (hasActions) {
            result += '\n</igx-grid-toolbar-actions>';
        }
        const toolbarChildren = (_p = toolbar) === null || _p === void 0 ? void 0 : _p.children.filter(child => child.name && !child.name.includes('toolbar'));
        toolbarChildren === null || toolbarChildren === void 0 ? void 0 : toolbarChildren.forEach(child => {
            const { startTag, endTag, file } = (0, util_1.getSourceOffset)(child);
            const replaceText = file.content.substring(startTag.start, endTag.end);
            result += '\n' + replaceText;
        });
        return result + `\n</igx-grid-toolbar>`;
    };
    const clearOldToolbar = (grid) => {
        const node = (0, util_1.findElementNodes)(grid, 'igx-grid-toolbar')[0];
        if (!node) {
            return;
        }
        const { startTag, endTag, file } = (0, util_1.getSourceOffset)(node);
        const replaceText = file.content.substring(startTag.start, endTag.end);
        addChange(file.url, new util_1.FileChange(startTag.start, '', replaceText, 'replace'));
        applyChanges();
        changes.clear();
    };
    const getExportText = (exporter, type) => {
        const element = exporter.children.find(el => {
            if (type === 'text' && !!el.value && el.value.trim().length > 0) {
                return el;
            }
            else if (!!el.attrs && (0, util_1.hasAttribute)(el, type)) {
                return el;
            }
            return undefined;
        });
        if (!element) {
            return '';
        }
        if (type !== 'text') {
            const { startTag, endTag, file } = (0, util_1.getSourceOffset)(element);
            const replaceText = file.content.substring(startTag.start, endTag.end);
            return { value: replaceText, template: true };
        }
        return element;
    };
    for (const path of update.templateFiles) {
        //update toolbar
        const tags = TAGS.slice(0, 3);
        (0, util_1.findElementNodes)((0, util_1.parseFile)(new HtmlParser(), host, path), tags)
            .filter(grid => (0, util_1.hasAttribute)(grid, toolbarProp))
            .map(node => (0, util_1.getSourceOffset)(node))
            .reverse()
            .forEach(offset => {
            const { startTag, file, node } = offset;
            const attributes = new Object();
            (0, util_1.getAttribute)(node, toolbarProp).forEach(attr => attributes[attr.name.replace(/[\[\]]+/g, '')] =
                { name: attr.name.replace(/[\[\]]+/g, ''), value: attr.value });
            const text = buildToolbar(node, attributes);
            clearOldToolbar(node);
            addChange(file.url, new util_1.FileChange(startTag.end, text));
            applyChanges();
            changes.clear();
        });
        //update row island in that file too
        (0, util_1.findElementNodes)((0, util_1.parseFile)(new HtmlParser(), host, path), 'igx-row-island')
            .filter(grid => (0, util_1.hasAttribute)(grid, toolbarProp))
            .map(node => (0, util_1.getSourceOffset)(node))
            .reverse()
            .forEach(offset => {
            const { startTag, file, node } = offset;
            const attributes = new Object();
            (0, util_1.getAttribute)(node, toolbarProp).forEach(attr => attributes[attr.name.replace(/[\[\]]+/g, '')] =
                { name: attr.name.replace(/[\[\]]+/g, ''), value: attr.value });
            const text = buildToolbar(node, attributes);
            clearOldToolbar(node);
            addChange(file.url, new util_1.FileChange(startTag.end, text));
            applyChanges();
            changes.clear();
        });
    }
    applyChanges();
    changes.clear();
    update.applyChanges();
});
