/**
 * @jest-environment jsdom
 */

/*
 * Copyright (c) 2023 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import eclipsefdnMembersList from '../eclipsefdn.members-list';
import * as interestGroupAPI from '../../api/eclipsefdn.interest-groups';
import { mockParticipatingOrganizationsCategorizedByInterestGroup } from '../../api/tests/mocks/interest-groups/mock-data';

describe('eclipsefdn-members-list', () => {
  let getInterestGroupParticipatingOrganizationsSpy;

  beforeEach(() => {
    getInterestGroupParticipatingOrganizationsSpy = jest.spyOn(
      interestGroupAPI,
      'getInterestGroupParticipatingOrganizations'
    );
  });

  // TODO: Remove skip once mustache-loader has been replaced with handlebars-loader.
  it.skip('Renders interest group members', async () => {
    const shortId = 'openmobility';
    const participatingOrganizations =
      mockParticipatingOrganizationsCategorizedByInterestGroup[shortId];

    getInterestGroupParticipatingOrganizationsSpy.mockReturnValue([
      participatingOrganizations,
      null,
    ]);

    document.querySelector('body').innerHTML = `
        <ul
            class="eclipsefdn-members-list"
            data-type="interest-group"
            data-id="${shortId}"
            data-ml-template="only-logos"
        >
        </ul>
    `;

    eclipsefdnMembersList.render();

    // This hack is needed to ensure the members-list has rendered but it is not guaranteed to work.
    // This should be replaced with `await render()` once eclipsefdn-members-list uses
    // `renderTemplate`.
    await new Promise(resolve => setTimeout(() => resolve(), 1000));

    expect(getInterestGroupParticipatingOrganizationsSpy).toHaveBeenCalledWith({
      interestGroupId: shortId,
    });

    const logoElements = Array.from(document.querySelectorAll('.eclipsefdn-members-list img'));

    // Fetching member names through alt text as they match one-to-one.
    const namesOfDisplayedMembers = logoElements
      .map(logoElement => logoElement.getAttribute('alt'))
      .sort();
    const participatingOrganizationNames = participatingOrganizations
      .map(organization => organization.name)
      .filter((value, i, arr) => arr.indexOf(value) === i)
      .sort();

    expect(namesOfDisplayedMembers).toEqual(participatingOrganizationNames);
  });

  it.skip('Shows member as text when no logo is present', async () => {
    const shortId = 'openmobility';

    // Mutating the first element of participating organizations to ensure the web logo is `null`.
    // Everything else is set to a url mock.
    let participatingOrganizations = mockParticipatingOrganizationsCategorizedByInterestGroup[shortId];
    participatingOrganizations.forEach((_, i) => participatingOrganizations[i].logos.web = 'some url');
    participatingOrganizations[0].logos.web = null;


    getInterestGroupParticipatingOrganizationsSpy.mockReturnValue([
      participatingOrganizations,
      null
    ]);

    document.querySelector('body').innerHTML = `
      <ul
        class="eclipsefdn-members-list"
        data-type="interest-group"
        data-id="${shortId}"
        data-ml-template="only-logos"
      >
      </ul>
    `;

    eclipsefdnMembersList.render();
    
    // This hack is needed to ensure the members-list has rendered but it is not guaranteed to work.
    // This should be replaced with `await render()` once eclipsefdn-members-list uses
    // `renderTemplate`.
    await new Promise(resolve => setTimeout(() => resolve(), 1000));
    
    // We expect one of the elements to not have a logo. So we subtract one.
    const expectedLogoCount = participatingOrganizations.length - 1;
    const renderedLogoCount = document.querySelectorAll('.eclipsefdn-members-list img').length;

    const placeholderTextElement = document.querySelector(`.eclipsefdn-members-list a[title="${participatingOrganizations[0].name}"]`);

    expect(renderedLogoCount).toEqual(expectedLogoCount);
    expect(placeholderTextElement.innerHTML).toEqual(participatingOrganizations[0].name);
  });

});
