import { addIndex, forEach } from 'ramda';

import { printError } from '../../lib';
import filterSizesByAspectRatio from './filterSizesByAspectRatio';
import { FEATURED_IMAGE_FIXTURE } from '../../../tests/fixtures/media';

jest.mock('../../lib/console');

describe('filterSizesByAspectRatio', () => {
  beforeAll(() => {
    // Suppress console logging when testing
    printError.mockImplementation(() => null);
  });

  const testCases = [
    { aspectRatio: '16:9',
      expected: {
        '1028x600': {
          source_url: 'path/to/1028x600', width: 1028, height: 600,
        },
        '640x360': {
          source_url: 'path/to/640x360', width: 640, height: 360,
        },
        '1024x576': {
          source_url: 'path/to/1024x576', width: 1024, height: 576,
        },
        '1024x574': {
          source_url: 'path/to/1024x574', width: 1024, height: 574,
        },
        '1024x579': {
          source_url: 'path/to/1024x579', width: 1024, height: 579,
        },
      },
    },
    {
      aspectRatio: '1:1',
      expected: {
        '1024x1022': {
          height: 1022, source_url: 'path/to/1024x1022', width: 1024,
        },
        '1024x1024': {
          height: 1024, source_url: 'path/to/1024x1024', width: 1024,
        },
        '1024x1026': {
          height: 1026, source_url: 'path/to/1024x1026', width: 1024,
        },
      },
    },
    {
      aspectRatio: '2:1',
      expected: {
        '1024x510': {
          height: 510, source_url: 'path/to/1024x510', width: 1024,
        },
        '1024x512': {
          height: 512, source_url: 'path/to/1024x512', width: 1024,
        },
        '1024x514': {
          height: 514, source_url: 'path/to/1024x514', width: 1024,
        },
      },
    },
  ];

  addIndex(forEach)(({ aspectRatio, expected }, index) => {
    it(`gets correct sizes for the passed aspect ratio #${index + 1}`, () => {
      const { media_details: { sizes } } = FEATURED_IMAGE_FIXTURE;
      expect(filterSizesByAspectRatio(sizes, aspectRatio)).toEqual(expected);
    });
  }, testCases);

  it('copes when supplied incorrect aspect ratio format', () => {
    expect(filterSizesByAspectRatio(FEATURED_IMAGE_FIXTURE.sizes))
      .toEqual({});
    expect(filterSizesByAspectRatio(FEATURED_IMAGE_FIXTURE.sizes, null))
      .toEqual({});
    expect(filterSizesByAspectRatio(FEATURED_IMAGE_FIXTURE.sizes, ''))
      .toEqual({});
  });

  it('logs error if invalid aspect ratio provided', () => {
    printError.mockClear();

    filterSizesByAspectRatio(FEATURED_IMAGE_FIXTURE, 'badFormat');

    expect(printError).toHaveBeenCalled();
    expect(printError).toHaveBeenCalledWith('Invalid aspect ratio provided.');
  });
});
