"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
var ramda_1 = require("ramda");
var react_2 = require("@testing-library/react");
var user_event_1 = __importDefault(require("@testing-library/user-event"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var MaskedAttributesContext_1 = require("../contexts/MaskedAttributesContext");
var MdmModuleContext_1 = require("../contexts/MdmModuleContext");
var SimpleAttribute_1 = require("./SimpleAttribute");
jest.mock('@reltio/mdm-sdk', function () { return (__assign(__assign({}, jest.requireActual('@reltio/mdm-sdk')), { getUnmaskedAttributeValue: jest.fn(), createActivity: jest.fn() })); });
describe('masking/unmasking behaviour', function () {
    beforeAll(function () {
        mdm_sdk_1.getUnmaskedAttributeValue.mockResolvedValue({
            value: 'Unmasked value',
            uri: 'entities/16U21B8f/attributes/Name/2sAfjGOIh'
        });
    });
    var defaultAttributeType = { type: 'String', name: 'Name', uri: 'URI', masking: { regexPattern: '.*' } };
    var defaultAttributeValue = { value: 'Masked value', uri: 'entities/16U21B8f/attributes/Name/2sAfjGOIh' };
    var defaultProps = {
        attributeType: defaultAttributeType,
        attributeValue: defaultAttributeValue
    };
    var defaultMdmValues = {
        entity: {
            uri: 'entities/16U21B8f',
            type: 'configuration/entityTypes/HCP',
            label: 'Test Entity'
        },
        metadata: {
            entityTypes: [
                {
                    uri: 'configuration/entityTypes/HCP',
                    attributes: [
                        {
                            uri: 'configuration/entityTypes/HCP/attributes/Nested',
                            name: 'Name',
                            label: 'Nested',
                            type: 'Nested',
                            attributes: [
                                {
                                    uri: 'configuration/entityTypes/HCP/attributes/Nested/attributes/TextField',
                                    label: 'Name Label',
                                    type: 'String',
                                    name: 'Name'
                                }
                            ]
                        },
                        {
                            uri: 'configuration/entityTypes/HCP/attributes/RDMLookup',
                            type: 'Reference',
                            label: 'RDMLookup Label',
                            name: 'RDMLookup'
                        }
                    ]
                }
            ]
        },
        showMasking: true,
        mode: mdm_sdk_1.Mode.Viewing
    };
    var setUp = function (props, mdmValues) {
        if (props === void 0) { props = defaultProps; }
        if (mdmValues === void 0) { mdmValues = defaultMdmValues; }
        var Providers = function (_a) {
            var children = _a.children;
            return (react_1.default.createElement(MdmModuleContext_1.MdmModuleProvider, { values: mdmValues },
                react_1.default.createElement(MaskedAttributesContext_1.MaskedAttributesProvider, null, children)));
        };
        var user = user_event_1.default.setup();
        return __assign({ user: user }, (0, react_2.render)(react_1.default.createElement(SimpleAttribute_1.SimpleAttribute, __assign({}, props)), {
            wrapper: Providers
        }));
    };
    afterEach(function () {
        jest.clearAllMocks();
    });
    it('should not render MaskingSwitcher if attribute should not be masked', function () {
        var attributeType = (0, ramda_1.dissoc)('masking', defaultAttributeType);
        var container = setUp(__assign(__assign({}, defaultProps), { attributeType: attributeType })).container;
        expect(container.querySelector('.switcherWrapper')).not.toBeInTheDocument();
    });
    it('should render MaskingSwitcher if attribute should be masked', function () {
        var container = setUp().container;
        expect(container.querySelector('.switcherWrapper')).toBeInTheDocument();
    });
    it('should call getUnmaskedAttributeValue when MaskingSwitcher is clicked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, container, user, switcher;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp(), container = _a.container, user = _a.user;
                    switcher = container.querySelector('.switcherWrapper');
                    return [4 /*yield*/, user.click(switcher)];
                case 1:
                    _b.sent();
                    expect(mdm_sdk_1.getUnmaskedAttributeValue).toHaveBeenCalledWith(defaultAttributeValue.uri);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render unmasked value when MaskingSwitcher is clicked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, container, user, switcher;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp(), container = _a.container, user = _a.user;
                    switcher = container.querySelector('.switcherWrapper');
                    expect(react_2.screen.getByText('Masked value')).toBeInTheDocument();
                    return [4 /*yield*/, user.click(switcher)];
                case 1:
                    _b.sent();
                    expect(react_2.screen.queryByText('Masked value')).not.toBeInTheDocument();
                    expect(react_2.screen.getByText('Unmasked value')).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render masked value when MaskingSwitcher is clicked twice', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, container, user;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp(), container = _a.container, user = _a.user;
                    expect(react_2.screen.getByText('Masked value')).toBeInTheDocument();
                    return [4 /*yield*/, user.click(container.querySelector('.switcherWrapper'))];
                case 1:
                    _b.sent();
                    expect(react_2.screen.queryByText('Masked value')).not.toBeInTheDocument();
                    expect(react_2.screen.getByText('Unmasked value')).toBeInTheDocument();
                    return [4 /*yield*/, user.click(container.querySelector('.switcherWrapper'))];
                case 2:
                    _b.sent();
                    expect(react_2.screen.getByText('Masked value')).toBeInTheDocument();
                    expect(react_2.screen.queryByText('Unmasked value')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render CircularProgress while unmasked attribute value is loading', function () { return __awaiter(void 0, void 0, void 0, function () {
        var resolveGetUnmaskedAttributeValue, _a, container, user, switcher;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    mdm_sdk_1.getUnmaskedAttributeValue.mockImplementationOnce(function () { return new Promise(function (resolve) { return (resolveGetUnmaskedAttributeValue = resolve); }); });
                    _a = setUp(), container = _a.container, user = _a.user;
                    switcher = container.querySelector('.switcherWrapper');
                    return [4 /*yield*/, user.click(switcher)];
                case 1:
                    _b.sent();
                    expect(react_2.screen.getByRole('progressbar')).toBeInTheDocument();
                    return [4 /*yield*/, (0, react_2.act)(function () { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                resolveGetUnmaskedAttributeValue({
                                    value: 'Unmasked value',
                                    uri: 'entities/16U21B8f/attributes/Name/2sAfjGOIh'
                                });
                                return [2 /*return*/];
                            });
                        }); })];
                case 2:
                    _b.sent();
                    return [4 /*yield*/, react_2.screen.findByText('Unmasked value')];
                case 3:
                    _b.sent();
                    expect(react_2.screen.queryByRole('progressbar')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not format date attribute if it is masked', function () {
        var attributeType = { type: 'Date', name: 'lastUpdateTime', uri: 'URI', masking: { regexPattern: '.*' } };
        var attributeValue = { value: '******0-16', uri: 'entities/16U21B8f/attributes/lastUpdateTime/1qWvQglW' };
        setUp({ attributeType: attributeType, attributeValue: attributeValue });
        expect(react_2.screen.getByText('******0-16')).toBeInTheDocument();
    });
    it('should not format timestamp attribute if it is masked', function () {
        var attributeType = { type: 'Timestamp', name: 'Timestamp', uri: 'URI', masking: { regexPattern: '.*' } };
        var attributeValue = { value: '**********0000', uri: 'entities/16U21B8f/attributes/Timestamp/1qWvQglW' };
        setUp({ attributeType: attributeType, attributeValue: attributeValue });
        expect(react_2.screen.getByText('**********0000')).toBeInTheDocument();
    });
    it('should call createActivity with correct arguments when MaskingSwitcher is clicked to unmask', function () { return __awaiter(void 0, void 0, void 0, function () {
        var attributeType, attributeValue, _a, container, user, switcher;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    attributeType = __assign(__assign({}, defaultAttributeType), { uri: 'configuration/entityTypes/HCP/attributes/Nested/attributes/TextField' });
                    attributeValue = __assign(__assign({}, defaultAttributeValue), { uri: 'entities/02ZRRE9/attributes/Nested/1bgW4Wj3/TextField/1bgW4nm5' });
                    _a = setUp({ attributeType: attributeType, attributeValue: attributeValue }), container = _a.container, user = _a.user;
                    switcher = container.querySelector('.switcherWrapper');
                    return [4 /*yield*/, user.click(switcher)];
                case 1:
                    _b.sent();
                    expect(mdm_sdk_1.createActivity).toHaveBeenCalledWith({
                        label: 'ATTRIBUTE_UNMASKED',
                        description: JSON.stringify({
                            uri: 'entities/16U21B8f',
                            label: 'Test Entity: Nested / Name Label - Masked value'
                        }),
                        items: [{ objectUri: 'entities/16U21B8f' }]
                    });
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not call createActivity if attribute is already unmasked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var unmaskedAttributeValue, _a, container, user, switcher;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    unmaskedAttributeValue = {
                        value: 'Unmasked value',
                        uri: defaultAttributeValue.uri
                    };
                    mdm_sdk_1.getUnmaskedAttributeValue.mockResolvedValue(unmaskedAttributeValue);
                    _a = setUp(), container = _a.container, user = _a.user;
                    switcher = container.querySelector('.switcherWrapper');
                    return [4 /*yield*/, user.click(switcher)];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, user.click(switcher)];
                case 2:
                    _b.sent();
                    expect(mdm_sdk_1.createActivity).toHaveBeenCalledTimes(1);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should log an error if createActivity request fails', function () { return __awaiter(void 0, void 0, void 0, function () {
        var consoleErrorSpy, _a, container, user, switcher;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    consoleErrorSpy = jest.spyOn(console, 'warn').mockImplementation();
                    mdm_sdk_1.createActivity.mockRejectedValue(new Error('API Error'));
                    _a = setUp(), container = _a.container, user = _a.user;
                    switcher = container.querySelector('.switcherWrapper');
                    return [4 /*yield*/, user.click(switcher)];
                case 1:
                    _b.sent();
                    expect(consoleErrorSpy).toHaveBeenCalledWith(new Error('API Error'));
                    consoleErrorSpy.mockRestore();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not render masking controls if showMasking configuration property is false', function () { return __awaiter(void 0, void 0, void 0, function () {
        var mdmValues, container;
        return __generator(this, function (_a) {
            mdmValues = __assign(__assign({}, defaultMdmValues), { showMasking: false });
            container = setUp(defaultProps, mdmValues).container;
            expect(container.querySelector('.switcherWrapper')).not.toBeInTheDocument();
            return [2 /*return*/];
        });
    }); });
});
