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 { BpSdkVehicleMakes } from "../bp-sdk-vehicle-makes/bp-sdk-vehicle-makes";
import { BpSdkVehicleMakesContainer } from "./bp-sdk-vehicle-makes-container";
const fakeStore = {
    viewState: {
        vehicleOptions: {
            selection: {
                testId: {
                    yearId: 2018,
                    makeId: '53',
                    modelId: '436357',
                    configurationId: '1440364',
                },
            },
            makes: {
                testId: {},
            },
        },
    },
};
const setupPage = async (additionalComponents = []) => {
    return await newSpecPage({
        html: '<bp-sdk-vehicle-makes-container question-group-id="testId"></bp-sdk-vehicle-makes-container>',
        components: [BpSdkVehicleMakesContainer, ...additionalComponents],
    });
};
const setupInstance = (page) => {
    const instance = page.rootInstance;
    instance.makeOptions = { test: 'Test Display' };
    instance.selectedVehicle = {
        yearId: 2018,
        makeId: '53',
        modelId: '436357',
        configurationId: '1440364',
    };
    instance.storeUnsubscribe = jest.fn();
    return instance;
};
describe('bp-sdk-vehicle-makes-container', () => {
    it('renders', async () => {
        const page = await setupPage();
        setupInstance(page);
        await page.waitForChanges();
        expect(page.root).toEqualHtml(`<bp-sdk-vehicle-makes-container question-group-id="testId">
          <bp-sdk-vehicle-makes answeredbysource="" label="Enter vehicle make" pristine="" selectedmakeid="53">
          </bp-sdk-vehicle-makes>
        </bp-sdk-vehicle-makes-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-makes-container question-group-id="testId">
          <bp-sdk-vehicle-makes answeredbysource="" label="Enter vehicle make" pristine="">
          </bp-sdk-vehicle-makes>
        </bp-sdk-vehicle-makes-container>`);
    });
    it('renders no makes', async () => {
        const page = await setupPage();
        const instance = setupInstance(page);
        instance.makeOptions = {};
        await page.waitForChanges();
        expect(page.root).toEqualHtml(`<bp-sdk-vehicle-makes-container question-group-id="testId"></bp-sdk-vehicle-makes-container>`);
    });
    it('renders make id', async () => {
        const page = await setupPage();
        const instance = setupInstance(page);
        instance.selectedVehicle = {
            makeId: 'testId',
        };
        await page.waitForChanges();
        expect(page.root).toEqualHtml(`<bp-sdk-vehicle-makes-container question-group-id="testId">
        <bp-sdk-vehicle-makes answeredbysource="" label="Enter vehicle make" pristine="" selectedmakeid="testId"></bp-sdk-vehicle-makes>
      </bp-sdk-vehicle-makes-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-makes-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('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('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('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: 'make', value: '', freeform: true, displayValue: '' });
        });
        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: 'make', value: 'test', freeform: false, displayValue: 'Test Display' });
        });
    });
    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('convertMakesToChoices', () => {
        it('converts makes to IChoice array', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const makes = { '1234': 'Test1', '4321': 'Test2' };
            expect(instance.convertMakesToChoices(makes)).toEqual([
                { id: '1234', value: 'Test1' },
                { id: '4321', value: 'Test2' },
            ]);
        });
        it('sorts makes in alphabetical order', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const makes = { '1234': 'Mitsubishi', '4321': 'Fiat', '6432': 'BMW', '9273': 'Maserati' };
            expect(instance.convertMakesToChoices(makes)).toEqual([
                { id: '6432', value: 'BMW' },
                { id: '4321', value: 'Fiat' },
                { id: '9273', value: 'Maserati' },
                { id: '1234', value: 'Mitsubishi' },
            ]);
        });
        it('returns empty array if there are no makes', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            expect(instance.convertMakesToChoices({})).toEqual([]);
        });
    });
    describe('mapStateToProps', () => {
        it('returns vehicleOptions', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            const result = instance.mapStateToProps(fakeStore);
            expect(result.makeOptions).toEqual(fakeStore.viewState.vehicleOptions.makes.testId);
            expect(result.selectedVehicle).toEqual(fakeStore.viewState.vehicleOptions.selection.testId);
        });
    });
    describe('internal state', () => {
        it('passes along code', async () => {
            const page = await setupPage([BpSdkVehicleMakes]);
            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();
            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();
            const instance = setupInstance(page);
            const detail = undefined;
            instance.filter = 'some old value';
            instance.onFilterUpdate({ detail });
            expect(instance.filter).toEqual('');
        });
    });
    describe('onMakesChange', () => {
        it('handles null data', async () => {
            const page = await setupPage();
            const instance = setupInstance(page);
            instance.makeOptions = undefined;
            expect(instance.value).toBeUndefined();
        });
    });
});
