jest.mock('@boldpenguin/sdk-utility', () => (Object.assign({
    // eslint-disable-next-line @typescript-eslint/naming-convention
    __esModule: true
}, jest.requireActual('@boldpenguin/sdk-utility'))));
import * as utils from "@boldpenguin/sdk-utility";
import { newSpecPage } from "@stencil/core/testing";
import { BpSdkVehicleModels } from "../bp-sdk-vehicle-models/bp-sdk-vehicle-models";
import { BpSdkVehicleModelsContainer } from "./bp-sdk-vehicle-models-container";
const fakeStore = {
    viewState: {
        vehicleOptions: {
            selection: {
                testId: {
                    yearId: 2018,
                    makeId: '53',
                    modelId: '436357',
                    configurationId: '1440364',
                },
            },
            models: {
                testId: {},
            },
        },
    },
};
const setupPage = async (additionalComponents = []) => {
    return await newSpecPage({
        html: '<bp-sdk-vehicle-models-container question-group-id="testId"></bp-sdk-vehicle-models-container>',
        components: [BpSdkVehicleModelsContainer, ...additionalComponents],
    });
};
const setupInstance = (page) => {
    const instance = page.rootInstance;
    instance.modelOptions = { testId: 'test' };
    instance.selectedVehicle = {
        yearId: 2018,
        makeId: '53',
        modelId: '436357',
        configurationId: '1440364',
    };
    instance.storeUnsubscribe = jest.fn();
    return instance;
};
describe('bp-sdk-vehicle-models-container', () => {
    it('renders', async () => {
        const page = await setupPage();
        const instance = setupInstance(page);
        const modelId = instance.selectedVehicle.modelId.toString();
        await page.waitForChanges();
        expect(page.root).toEqualHtml(`<bp-sdk-vehicle-models-container  question-group-id="testId">
        <bp-sdk-vehicle-models answeredbysource="" label="Enter vehicle model" pristine="" selectedmodelid="${modelId}"></bp-sdk-vehicle-models>
      </bp-sdk-vehicle-models-container>`);
    });
    it('renders no selection', async () => {
        const page = await setupPage();
        const instance = setupInstance(page);
        instance.selectedVehicle = undefined;
        await page.waitForChanges();
        expect(page.root).toEqualHtml(`<bp-sdk-vehicle-models-container  question-group-id="testId">
        <bp-sdk-vehicle-models answeredbysource="" label="Enter vehicle model" pristine=""></bp-sdk-vehicle-models>
      </bp-sdk-vehicle-models-container>`);
    });
    it('renders no models', async () => {
        const page = await setupPage();
        const instance = setupInstance(page);
        instance.modelOptions = {};
        const modelId = instance.selectedVehicle.modelId.toString();
        await page.waitForChanges();
        expect(page.root).toEqualHtml(`<bp-sdk-vehicle-models-container  question-group-id="testId">
        <bp-sdk-vehicle-models answeredbysource="" label="Enter vehicle model" pristine="" selectedmodelid="${modelId}"></bp-sdk-vehicle-models>
      </bp-sdk-vehicle-models-container>`);
    });
    it('renders modelId', async () => {
        const page = await setupPage();
        const instance = setupInstance(page);
        instance.selectedVehicle = {
            modelId: 'id',
        };
        await page.waitForChanges();
        expect(page.root).toEqualHtml(`<bp-sdk-vehicle-models-container question-group-id="testId"><bp-sdk-vehicle-models answeredbysource="" label="Enter vehicle model" pristine="" selectedmodelid="id"></bp-sdk-vehicle-models></bp-sdk-vehicle-models-container>`);
    });
    it('renders external component if defined', async () => {
        const whenDefinedMock = jest.spyOn(customElements, 'whenDefined').mockResolvedValueOnce({});
        const page = await setupPage();
        const element = page.root.querySelector('bp-sdk-external-vehicle-models-container');
        expect(element).toBeTruthy();
        whenDefinedMock.mockRestore();
    });
    describe('componentDidLoad', () => {
        it('makes expected calls', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            jest.spyOn(instance, 'loadFocusEvents').mockImplementation(() => { });
            instance.componentDidLoad();
            expect(instance.loadFocusEvents).toBeCalledTimes(1);
        });
    });
    describe('disconnectedCallback', () => {
        it('makes expected calls', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            jest.spyOn(instance, 'unloadFocusEvents').mockImplementation(() => { });
            jest.spyOn(instance, 'storeUnsubscribe').mockImplementation(() => { });
            instance.disconnectedCallback();
            expect(instance.unloadFocusEvents).toBeCalledTimes(1);
            expect(instance.storeUnsubscribe).toBeCalledTimes(1);
        });
    });
    describe('onMakeDirty', () => {
        it('should ignore unchanged touched state', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.touched = false;
            instance.pristine = true;
            instance.onMakeDirty();
            expect(instance.touched).toBeTruthy();
            expect(instance.pristine).toBeFalsy();
        });
    });
    describe('onUseExternalChange', () => {
        it('makes expected calls if true', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            jest.spyOn(instance, 'unloadFocusEvents').mockImplementation(() => { });
            instance.onUseExternalChange(true);
            expect(instance.unloadFocusEvents).toBeCalledTimes(0);
        });
        it('makes expected calls if false', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            jest.spyOn(instance, 'unloadFocusEvents').mockImplementation(() => { });
            instance.onUseExternalChange(false);
            expect(instance.unloadFocusEvents).toBeCalledTimes(1);
        });
    });
    describe('loadFocusEvents', () => {
        it('sets expected values', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.useExternal = false;
            jest.spyOn(instance.el, 'addEventListener').mockReturnValue();
            await page.waitForChanges();
            instance.loadFocusEvents();
            expect(instance.el.addEventListener).toBeCalledTimes(1);
            expect(instance.el.addEventListener).toBeCalledWith('focusout', instance.onFocusOut);
        });
        it('handles truthy useExternal', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.useExternal = true;
            jest.spyOn(instance.el, 'addEventListener').mockReturnValue();
            await page.waitForChanges();
            instance.loadFocusEvents();
            expect(instance.el.addEventListener).toBeCalledTimes(0);
        });
    });
    describe('unloadFocusEvents', () => {
        it('sets expected values', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            jest.spyOn(instance.el, 'removeEventListener').mockImplementation(() => { });
            await page.waitForChanges();
            instance.unloadFocusEvents();
            expect(instance.el.removeEventListener).toBeCalledTimes(1);
            expect(instance.el.removeEventListener).toBeCalledWith('focusout', instance.onFocusOut);
        });
    });
    describe('onValueUpdate', () => {
        it('sets expected values', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.pristine = true;
            instance.onValueUpdate({ detail: [''] });
            expect(instance.pristine).toBeFalsy();
            expect(instance.value).toEqual('');
        });
        it('handles no details', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.pristine = true;
            instance.onValueUpdate({ detail: undefined });
            expect(instance.pristine).toBeFalsy();
            expect(instance.value).toBeUndefined();
        });
        it('handles truthy useExternal', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.useExternal = true;
            instance.pristine = true;
            instance.onValueUpdate({ detail: [''] });
            expect(instance.pristine).toBeTruthy();
            expect(instance.value).toBeUndefined();
        });
        it('emits event if no errors', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            jest.spyOn(instance.ymmcUpdate, 'emit').mockReturnValue(null);
            instance.onValueUpdate({ detail: [''] });
            expect(instance.ymmcUpdate.emit).toHaveBeenCalledWith({ type: 'model', freeform: true, value: '' });
        });
        it('does not emit event if there are errors', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.errors = ['required'];
            jest.spyOn(instance, 'updateErrors').mockReturnValue(null);
            jest.spyOn(instance.ymmcUpdate, 'emit').mockReturnValue(null);
            instance.onValueUpdate({ detail: [''] });
            expect(instance.ymmcUpdate.emit).not.toHaveBeenCalled();
        });
        it('updates errors if value would fix required error', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.errors = ['required'];
            jest.spyOn(instance.ymmcUpdate, 'emit').mockReturnValue(null);
            instance.onValueUpdate({ detail: ['test'] });
            expect(instance.ymmcUpdate.emit).toHaveBeenCalledWith({ type: 'model', freeform: true, value: 'test' });
        });
    });
    describe('onFocusOut', () => {
        it('sets expected values', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.touched = false;
            instance.onFocusOut();
            expect(instance.touched).toBeTruthy();
        });
    });
    describe('updateErrors', () => {
        it('returns required if error determined', async () => {
            jest.spyOn(utils, 'hasRequiredError').mockReturnValue(true);
            const page = await setupPage();
            const instance = setupInstance(page);
            await page.waitForChanges();
            instance.updateErrors(false, false, '');
            expect(instance.errors).toEqual(['required']);
        });
        it('otherwise empty state', async () => {
            jest.spyOn(utils, 'hasRequiredError').mockReturnValue(false);
            const page = await setupPage();
            const instance = setupInstance(page);
            await page.waitForChanges();
            instance.updateErrors(false, false, '');
            expect(instance.errors).toEqual([]);
        });
    });
    describe('convertModelsToChoices', () => {
        it('converts models to IChoice array', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const models = { '1234': 'Test1', '4321': 'Test2' };
            expect(instance.convertModelsToChoices(models)).toEqual([
                { id: '1234', value: 'Test1' },
                { id: '4321', value: 'Test2' },
            ]);
        });
        it('sorts them in alphabetical order', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const models = { '1234': 'FJ Cruiser', '4321': 'Alphard', '4328': 'Yaris' };
            expect(instance.convertModelsToChoices(models)).toEqual([
                { id: '4321', value: 'Alphard' },
                { id: '1234', value: 'FJ Cruiser' },
                { id: '4328', value: 'Yaris' },
            ]);
        });
        it('returns empty array if there are no models', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            expect(instance.convertModelsToChoices({})).toEqual([]);
        });
    });
    describe('mapStateToProps', () => {
        it('returns vehicleOptions', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const result = instance.mapStateToProps(fakeStore);
            expect(result.modelOptions).toEqual(fakeStore.viewState.vehicleOptions.models.testId);
            expect(result.selectedVehicle).toEqual(fakeStore.viewState.vehicleOptions.selection.testId);
        });
    });
    describe('internal state', () => {
        it('passes along code', async () => {
            const page = await setupPage([BpSdkVehicleModels]);
            const instance = setupInstance(page);
            instance.code = 'oldCode';
            await page.waitForChanges();
            const ele = page.root.querySelector('bp-sdk-dynamic-input');
            expect(ele).toEqualAttribute('code', 'oldCode');
        });
    });
    describe('handleSubscriptions', () => {
        it('calls unsubscribe if subscribed', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const unsubscribe = jest.fn();
            instance.storeUnsubscribe = unsubscribe;
            instance.handleSubscriptions();
            expect(unsubscribe).toHaveBeenCalled();
        });
        it('overwrites an existing subscribe function', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const unsubscribe = jest.fn();
            instance.storeUnsubscribe = unsubscribe;
            instance.handleSubscriptions();
            expect(instance.storeUnsubscribe).not.toEqual(unsubscribe);
            expect(instance.storeUnsubscribe).toBeDefined();
        });
        it('subscribes if not subscribed', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.storeUnsubscribe = null;
            instance.handleSubscriptions();
            expect(instance.storeUnsubscribe).not.toBeNull();
        });
        it('subscribes updates mapStateToProps if already has storeUnsubscribe', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const unsubscribe = jest.fn();
            instance.storeUnsubscribe = unsubscribe;
            instance.handleSubscriptions();
            expect(unsubscribe).toHaveBeenCalledTimes(1);
            expect(instance.storeUnsubscribe).not.toEqual(unsubscribe);
        });
    });
    describe('connectedCallback', () => {
        it('makes expected call if root available', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.handleSubscriptions = jest.fn();
            jest.spyOn(instance.el, 'querySelector').mockImplementationOnce(() => ({
                componentOnReady: () => Promise.resolve(true),
            }));
            instance.connectedCallback();
            await page.waitForChanges();
            expect(instance.handleSubscriptions).toBeCalledTimes(1);
        });
    });
    describe('onFilterUpdate', () => {
        it('sets filter prop with detail', async () => {
            const page = await setupPage([BpSdkVehicleModels]);
            const instance = setupInstance(page);
            const detail = { id: 'id', value: 'value' };
            instance.filter = '';
            instance.onFilterUpdate({ detail });
            expect(instance.filter).toEqual(detail.value);
        });
        it('handles null detail', async () => {
            const page = await setupPage([BpSdkVehicleModels]);
            const instance = setupInstance(page);
            const detail = undefined;
            instance.filter = 'some old value';
            instance.onFilterUpdate({ detail });
            expect(instance.filter).toEqual('');
        });
    });
});
