import { BORDER_WIDTH_CONST, maskStyles } from './western-world.utils.constants';

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

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

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

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 getMaskStyles = cell => {
  const borderWidth = BORDER_WIDTH_CONST / cell.location.size;
  const borderMaskStylesByCell = `
    use.use-border {
      stroke: black;
      stroke-width: ${borderWidth}px;
    }
  `;
  return `
    ${maskStyles}
    ${borderMaskStylesByCell}  
  `;
};
