export const getPathDByData = (dData, k) => {
  return dData.reduce((previousValue, el) => {
    switch (el.type) {
      case 'M':
        return (previousValue += `M${el.x * k} ${el.y * k} `);
      case 'L':
        return (previousValue += `L${el.x * k} ${el.y * k} `);
      case 'Q':
        return (previousValue += `Q${el.x * k} ${el.y * k} ${el.x1 * k} ${el.y1 * k}`);
      case 'Z':
        return (previousValue += `Z`);
    }
  }, '');
};

export const getPathByCell = (cell, maxCellSize, maxMainSvgViewBox) => {
  const k = maxMainSvgViewBox / maxCellSize;
  if (cell.svg.type === 'path') {
    const d = getPathDByData(cell.svg.dData, k);
    return `<path id="path-border-${cell.id}" d="${d}"></path>`;
  }
  if (cell.svg.type === 'circle') {
    return `<circle id="path-border-${cell.id}" cx="${cell.svg.cx * k}" cy="${cell.svg.cy * k}" r="${
      cell.svg.r * k
    }"></circle>`;
  }
};

export const getImageByUrl = (url) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = url;
    img.onload = () => {
      resolve(img);
    };
  });
};

export const getFlagsArray = (prefix) => {
  return new Array(6).fill(null).map((_, index) => ({
    name: `${prefix}-flag-stars-${index}`,
    starsN: index,
    prefix,
    index,
  }));
};

export const buildImageForCanvasFromHtmlStr = (htmlStr) => {
  return new Promise((resolve) => {
    const DOMURL = window.URL || window;
    const img = new Image();
    const svgBlob = new Blob([htmlStr], { type: 'image/svg+xml' });
    const url = DOMURL.createObjectURL(svgBlob);
    img.onload = () => {
      DOMURL.revokeObjectURL(img);
      resolve(img);
    };
    img.src = url;
  });
};

export const didStarsChange = (currentGameValue, previousGameValue) => {
  return Object.keys(currentGameValue.stocks).some(
    (firmId) => currentGameValue.stocks[firmId].stars !== previousGameValue.stocks[firmId].stars
  );
};

export const shouldRedraw = (currentGameValue, previousGameValue) => {
  if (!previousGameValue) {
    return true;
  }
  let isPlayersFirmsChanged;

  // deep compare player's firms;
  if (previousGameValue) {
    isPlayersFirmsChanged = previousGameValue.players.order.some((playerIdKey) => {
      if (!currentGameValue.players[playerIdKey]) {
        // player was droped or lost;
        return true;
      }
      return (
        currentGameValue.players[playerIdKey].firms.length !== previousGameValue.players[playerIdKey].firms.length ||
        didStarsChange(currentGameValue, previousGameValue)
      );
    });
  }

  return isPlayersFirmsChanged;
};

export const getMaxSide = (cell) => {
  const width = cell.location.x2 - cell.location.x1;
  const height = cell.location.y2 - cell.location.y1;
  return width > height ? width : height;
};
