import { v4 as uuid } from 'uuid';
import arraybufferToString from 'arraybuffer-to-string';

export const sortArrayRand = (array) => {
  return array
    .map((a) => [Math.random(), a])
    .sort((a, b) => a[0] - b[0])
    .map((a) => a[1]);
};

export const contentPhoneReplace = (str, phoneNumber) => {
  const regex = /(?:[-+() |\.]*\d){9,11}/g;
  return str.replace(regex, ` ${phoneNumber} `);
};

export const filterObject = (obj, listKey = []) => {
  const result = {};
  Object.keys(obj).forEach((key) => {
    if (listKey.includes(key)) {
      result[key] = obj[key];
    }
  });
  return result;
};

export const ignoreObject = (obj, listIgnore = []) => {
  const result = {};

  Object.keys(obj).forEach((key) => {
    if (!listIgnore.includes(key)) {
      result[key] = obj[key];
    }
  });

  return result;
};

export const parseBody = (body) => {
  try {
    return JSON.parse(arraybufferToString(body.raw[0].bytes));
  } catch (error) {
    return null;
  }
};

export const genUuid = () => {
  return uuid();
};

export const cloneObject = (obj = {}) => {
  return JSON.parse(JSON.stringify(obj));
};

export const extractKeywordLine = (input) => {
  return input
    .split('\n')
    .map((line) => {
      let [keyword, price] = line.split('\t');

      if (!(keyword && price)) {
        [keyword, price] = line.split(',');
      }

      if (!(keyword && price)) {
        [keyword, price] = line.split(';');
      }

      if (!(keyword && price)) {
        [keyword, price] = line.split('|');
      }

      if (!(keyword && price)) {
        [keyword, price] = line.split(':');
      }

      if (!(keyword && price)) {
        return null;
      }

      return {
        keyword: keyword.trim(),
        price: Number(price),
      };
    })
    .filter((item) => item);
};
