import {
  CONFIRMED,
  PROCESSED,
  PROCESSING,
} from '@orderingstack/front-components-common';

export const getElements = (lines: any[]) => {
  const toPrepare: string[] = [];
  const toDone: string[] = [];
  const allDone: string[] = [];
  const toConfirm: string[] = [];

  lines.forEach((line) => {
    if (line.status === CONFIRMED) {
      toPrepare.push(line.id);
      toDone.push(line.id);
    } else if (line.status === PROCESSING) {
      toConfirm.push(line.id);
      toDone.push(line.id);
    } else if (line.status === PROCESSED) {
      allDone.push(line.id);
    }
  });
  return { toPrepare, toDone, allDone, toConfirm };
};

export const shoudShowDeliverButton = (toDone: string[]) =>
  toDone && toDone.length > 0;

export const showDeliveredButton = (allDone: string[], toDone: string[]) =>
  allDone && allDone.length > 0 && toDone && toDone.length === 0;

export const getBackgroundColor = (
  allDone: string[],
  toDone: string[],
  toConfirm: string[],
  toPrepare: string[]
): string => {
  if (
    toPrepare &&
    toPrepare.length === 0 &&
    toConfirm &&
    toConfirm.length > 0
  ) {
    return '#4CAF50';
  }
  if (
    allDone &&
    allDone.length > 0 &&
    toDone &&
    toDone.length === 0 &&
    toConfirm &&
    toConfirm.length === 0
  ) {
    return '#ddd';
  }
  return '#ffc200';
};

export function groupLines(array: any[]) {
  const result: any[] = [];
  array.reduce((res: any, value: any) => {
    if (!res[value.hash]) {
      res[value.hash] = {
        ...value,
        quantity: 0,
        discounted: 0,
        discounts: [],
        firstProductQuantity: value.quantity,
        itemsToRemove: [],
      };

      result.push(res[value.hash]);
    }
    res[value.hash].quantity += value.quantity;
    res[value.hash].itemsToRemove.push(value.id);
    if (value.discounts) {
      if (!res[value.hash].discounts) {
        res[value.hash].discounts = [];
      }
      res[value.hash].discounts = res[value.hash].discounts.concat(
        value.discounts
      );
      res[value.hash].discounted = 0;
      for (let i = 0; i < res[value.hash].discounts.length; i += 1) {
        if (res[value.hash].discounts[i]) {
          res[value.hash].discounted += parseFloat(
            res[value.hash].discounts[i].discountPrice
          );
        }
      }
    }
    return res;
  }, {});

  return result;
}
