"use strict";
// © 2022 SolarWinds Worldwide, LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to
//  deal in the Software without restriction, including without limitation the
//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//  sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Helpers = exports.Animations = void 0;
exports.getCurrentBranchName = getCurrentBranchName;
exports.assertA11y = assertA11y;
const tslib_1 = require("tslib");
const fs = tslib_1.__importStar(require("fs"));
const path = tslib_1.__importStar(require("path"));
const perf_hooks_1 = require("perf_hooks");
const protractor_1 = require("protractor");
const atom_1 = require("./atom");
const Camera_1 = require("./virtual-camera/Camera");
var Animations;
(function (Animations) {
    Animations[Animations["ALL"] = 0] = "ALL";
    Animations[Animations["TRANSITIONS"] = 1] = "TRANSITIONS";
    Animations[Animations["TRANSFORMS"] = 2] = "TRANSFORMS";
    Animations[Animations["ANIMATIONS"] = 3] = "ANIMATIONS";
    Animations[Animations["TRANSFORMS_AND_ANIMATIONS"] = 4] = "TRANSFORMS_AND_ANIMATIONS";
    Animations[Animations["TRANSITIONS_AND_ANIMATIONS"] = 5] = "TRANSITIONS_AND_ANIMATIONS";
    Animations[Animations["TRANSITIONS_AND_TRANSFORMS"] = 6] = "TRANSITIONS_AND_TRANSFORMS";
})(Animations || (exports.Animations = Animations = {}));
function getCurrentBranchName(potentialGitRoot = process.cwd()) {
    const gitHeadPath = `${potentialGitRoot}/.git/HEAD`;
    if (!fs.existsSync(potentialGitRoot)) {
        return undefined;
    }
    if (fs.existsSync(gitHeadPath)) {
        // Taking last two fragments of branch name, usually it is formatted like branch_type/branch_name
        return fs
            .readFileSync(gitHeadPath, "utf-8")
            .trim()
            .split("/")
            .slice(2)
            .join("/");
    }
    // Recursively looking for git folder
    return getCurrentBranchName(path.resolve(potentialGitRoot, ".."));
}
function assertA11y(browser, atomClassOrSelector, disabledRules) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const AxeBuilder = require("@axe-core/webdriverjs");
        const selector = typeof atomClassOrSelector === "string"
            ? atomClassOrSelector
            : atom_1.Atom.getSelector(atomClassOrSelector);
        const accessibilityScanResults = yield new AxeBuilder(browser.driver)
            .include(selector)
            .disableRules(disabledRules || [])
            .analyze();
        expect(accessibilityScanResults.violations).toEqual([]);
    });
}
class Helpers {
    static prepareBrowser(pageName) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let url = "";
            if (pageName) {
                url += "#/" + pageName;
            }
            yield protractor_1.browser.angularAppRoot("app");
            yield protractor_1.browser.get(url);
            yield protractor_1.browser.waitForAngular();
            protractor_1.browser.clearMockModules();
        });
    }
    static prepareCamera(testName, suiteName) {
        return new Camera_1.Camera().loadFilm(protractor_1.browser, testName, suiteName);
    }
    static getElementByXpath(elementXpath) {
        return protractor_1.browser.driver.findElement(protractor_1.by.xpath(elementXpath));
    }
    static getElementByCSS(elementCSS) {
        return protractor_1.browser.driver.findElement(protractor_1.by.css(elementCSS));
    }
    static setCustomWidth(size, id) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return protractor_1.browser.executeScript(`document.getElementById("${id}").style.width = "${size}"`);
        });
    }
    static browserZoom(percent) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return protractor_1.browser.executeScript(`document.body.style.zoom='${percent}%'`);
        });
    }
    static pressKey(key_1) {
        return tslib_1.__awaiter(this, arguments, void 0, function* (key, times = 1) {
            while (times > 0) {
                yield protractor_1.browser.actions().sendKeys(key).perform();
                times--;
            }
        });
    }
    static clickOnEmptySpace() {
        return tslib_1.__awaiter(this, arguments, void 0, function* (x = 0, y = 0) {
            return protractor_1.browser.executeScript("document.elementFromPoint(arguments[0],arguments[1]).click()", x, y);
        });
    }
    static switchDarkTheme(mode) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const htmlClassList = `document.getElementsByTagName("html")[0].classList`;
            const script = mode === "on"
                ? `${htmlClassList}.add("dark-nova-theme")`
                : `${htmlClassList}.remove("dark-nova-theme")`;
            yield protractor_1.browser.executeScript(script);
        });
    }
    /**
     * TODO: make this method configurable, so that we would be able to partly disable
     * or enable the animations:
     *
     * https://jira.solarwinds.com/browse/NUI-2034
     */
    static disableCSSAnimations(type) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let disableTransitions = "-o-transition-property: none !important;" +
                "-moz-transition-property: none !important;" +
                "-ms-transition-property: none !important;" +
                "-webkit-transition-property: none !important;" +
                "transition-property: none !important;";
            let disableTransforms = "-o-transform: none !important;" +
                "-moz-transform: none !important;" +
                "-ms-transform: none !important;" +
                "-webkit-transform: none !important;" +
                "transform: none !important;";
            let disableAnimations = "-webkit-animation: none !important;" +
                "-moz-animation: none !important;" +
                "-o-animation: none !important;" +
                "-ms-animation: none !important;" +
                "animation: none !important;";
            switch (type) {
                case Animations.ALL:
                    break;
                case Animations.TRANSITIONS:
                    disableTransforms = "";
                    disableAnimations = "";
                    break;
                case Animations.TRANSFORMS:
                    disableAnimations = "";
                    disableTransitions = "";
                    break;
                case Animations.ANIMATIONS:
                    disableTransforms = "";
                    disableTransitions = "";
                    break;
                case Animations.TRANSFORMS_AND_ANIMATIONS:
                    disableTransitions = "";
                    break;
                case Animations.TRANSITIONS_AND_ANIMATIONS:
                    disableTransforms = "";
                    break;
                case Animations.TRANSITIONS_AND_TRANSFORMS:
                    disableAnimations = "";
                    break;
            }
            const css = "*, *:before, *:after {" +
                disableTransitions +
                disableTransforms +
                disableAnimations +
                "}";
            return protractor_1.browser.executeScript(`
            var head = document.head || document.getElementsByTagName("head")[0];
                            var style = document.createElement("style");
                            style.type = "text/css";
                            style.appendChild(document.createTextNode("${css}"));
            head.appendChild(style);
        `);
        });
    }
    static saveScreenShot(filename) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return protractor_1.browser.takeScreenshot().then((data) => {
                const stream = fs.createWriteStream(filename);
                stream.write(Buffer.from(data, "base64"));
                stream.end();
            });
        });
    }
    static setLocation(url) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return protractor_1.browser.executeScript((pUrl) => (window.location.href = `/#/${pUrl}`), url);
        });
    }
    static delayPromise(timeout) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve) => {
                setTimeout(() => resolve(), timeout);
            });
        });
    }
    static timed(fn_1) {
        return tslib_1.__awaiter(this, arguments, void 0, function* (fn, name = fn.name) {
            const start = perf_hooks_1.performance.now();
            try {
                return yield fn();
            }
            finally {
                const stop = perf_hooks_1.performance.now();
                console.log(`timed [${name}] took ${stop - start} ms`);
            }
        });
    }
    static waitElementVisible(el) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            yield protractor_1.browser.wait(protractor_1.protractor.ExpectedConditions.visibilityOf(el), 5000, "Element is not visible");
        });
    }
    static waitElementToBeClickable(el) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            yield protractor_1.browser.wait(protractor_1.protractor.ExpectedConditions.elementToBeClickable(el), 5000, "Element is not visible");
        });
    }
}
exports.Helpers = Helpers;
//# sourceMappingURL=helpers.js.map