import {
  BREAKPOINTS,
  BYTE_UNITS,
  ITEM_TYPES,
  ITEM_TYPE_DEFS,
} from '../constants';
import ALIAS from '../config/parameters/alias';
import uiConfig from '../config/ui/config';

export function filterInvestigations(investigations, predicate) {
  return {
    ...investigations,
    data: investigations.data.filter(predicate),
  };
}

export function getCurrentBreakpoint() {
  const width = window.innerWidth;
  return width
    ? Object.entries(BREAKPOINTS).find(([, w]) => width < w)[0]
    : 'md';
}

export function getDatasetParameterByName(dataset, parameterName) {
  const parameter = dataset.parameters.find((o) => o.name === parameterName);
  if (parameter && parameter.value) {
    return parameter.value;
  }
}

export function getDatasetParameterByPrefixName(dataset, prefix) {
  const parameters = JSON.parse(JSON.stringify(dataset.parameters));
  return parameters
    .filter((p) => p.name.startsWith(prefix))
    .map((p) => ({ ...p, name: ALIAS[p.name] || p.name }));
}

export function getDatasetParameterValueByName(dataset, name) {
  const sampleNameParameter = dataset.parameters.filter((o) => o.name === name);
  if (sampleNameParameter.length > 0) {
    return sampleNameParameter[0].value;
  }
}

/**
 * Returns a friendly readable string with the size
 * @param {integer} size Size in bytes
 */
export function stringifyBytesSize(size) {
  if (size === undefined) {
    return '';
  }

  for (const [i, unit] of BYTE_UNITS.entries()) {
    const multiplier = 1024 ** (BYTE_UNITS.length - i);

    if (size >= multiplier) {
      return `${(size / multiplier).toFixed(1)} ${unit}`;
    }
  }

  return `${size} Bytes`;
}

export function itemsFormatter(items) {
  const counts = items.reduce(
    (counts, { type }) => {
      counts[type] += 1;
      return counts;
    },
    { [ITEM_TYPES.SampleSheet]: 0, [ITEM_TYPES.Tool]: 0, [ITEM_TYPES.Other]: 0 }
  );

  return Object.entries(counts)
    .map(([type, count]) => {
      const { countLabel } = ITEM_TYPE_DEFS[type];
      return `${count} ${count > 1 ? `${countLabel}s` : countLabel}`;
    })
    .join(', ');
}

export function getSamplePageURL(sample) {
  if (!sample.parameters) {
    return undefined;
  }

  const parameter = sample.parameters.find(
    (parameter) => parameter.name === 'Id'
  );
  if (!parameter) {
    return undefined;
  }

  return `${uiConfig.samplePageTemplateURL}${parameter.value}`;
}

export function addAddressIfAbsent(addresses, addressToAdd) {
  if (
    !addressToAdd ||
    addresses.find((addr) => addr._id === addressToAdd._id)
  ) {
    return addresses;
  }

  return [addressToAdd, ...addresses];
}

export function makeFullScreen(img) {
  if (img.style.height && img.style.width) {
    // This test prevents bad image resizing out of fullscreen mode in case the user clicks several times on the image when it is in fullscreen mode.
    const originalHeightByStyle = img.style.height;
    const originalWidthByStyle = img.style.width;

    img.setAttribute('style', '');
    img.setAttribute('originalHeightByStyle', originalHeightByStyle);
    img.setAttribute('originalWidthByStyle', originalWidthByStyle);
  }

  img.onfullscreenchange = function handleFullscreenChange(event) {
    const img = event.target;
    const isFullscreen = document.fullscreenElement === img;

    if (!isFullscreen) {
      // img goes out of fullscreen mode
      img.style.height = img.getAttribute('originalHeightByStyle');
      img.style.width = img.getAttribute('originalWidthByStyle');
      img.style.cursor = 'zoom-in';
    }
  };

  img.onwebkitfullscreenchange = img.onfullscreenchange;
  img.onmozfullscreenchange = img.onfullscreenchange;
  img.onMSFullscreenChange = img.onfullscreenchange;

  try {
    if (img.requestFullscreen) {
      img.requestFullscreen();
    } else if (img.msRequestFullscreen) {
      img.msRequestFullscreen();
    } else if (img.mozRequestFullScreen) {
      img.mozRequestFullScreen();
    } else if (img.webkitRequestFullscreen) {
      img.webkitRequestFullscreen();
    } else {
      console.log('Fullscreen API is not supported');
    }
  } catch {
    console.log('make full screen not supported');
  }
}
