import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import TagListPanel from '../../components/Logbook/Tag/TagListPanel';

const resources = require('./resources/TagListPanel.resource.js');

require('it-each')({ testPerIteration: true });

describe('TagListPanelUnitTests', () => {
  beforeEach(() => {
    Enzyme.configure({ adapter: new Adapter() });
  });

  describe('rendering', () => {
    it.each(resources.rendering, '%s', ['description'], (element, next) => {
      const wrapper = getShallowedWrapper({
        availableTags: element.tags,
        isTagEditionEnabled: element.isTagEditionEnabled,
      });
      if (element.tags.length > 0) {
        expect(wrapper.find('TagListPanelLine').length).toBe(2);
        expect(wrapper.find('TagListPanelLine').at(0).prop('tag')).toEqual(
          element.tags[0]
        );
        expect(wrapper.find('TagListPanelLine').at(1).prop('tag')).toEqual(
          element.tags[1]
        );
      } else {
        expect(wrapper.get(0)).toBeNull();
      }
      next();
    });
  });

  describe('testFunctionalProps', () => {
    it('calls onEditButtonClicked when the user clicks the edit button', () => {
      const resource = resources.testFunctionalProps;
      const mockedOnEditButtonClicked = jest.fn();
      const wrapper = getShallowedWrapper({
        availableTags: resource.tags,
        isTagEditionEnabled: resource.isTagEditionEnabled,
        onEditButtonClicked: mockedOnEditButtonClicked,
      });
      expect(mockedOnEditButtonClicked).toHaveBeenCalledTimes(0);
      wrapper.find('TagListPanelLine').dive().find('Button').simulate('click');
      expect(mockedOnEditButtonClicked).toHaveBeenCalledTimes(1);
    });
  });
});

/** Get a shallowed wrapper */
function getShallowedWrapper(propsObject) {
  return Enzyme.shallow(
    <TagListPanel
      availableTags={propsObject.availableTags ? propsObject.availableTags : []}
      onEditButtonClicked={
        propsObject.onEditButtonClicked
          ? propsObject.onEditButtonClicked
          : () => null
      }
      isTagEditionEnabled={propsObject.isTagEditionEnabled}
    />
  );
}
