import {INumberObject} from "./types";

export function getPropByString(obj: any, propString: string) {
  if (!propString) return obj;

  var prop,
    props = propString.split(".");

  for (var i = 0, iLen = props.length - 1; i < iLen; i++) {
    prop = props[i];

    var candidate = obj[prop];
    if (candidate !== undefined) {
      obj = candidate;
    } else {
      break;
    }
  }

  if (props[i]) {
    return obj[props[i]];
  } else return null;
}

export const mapCountByProp = (arr: any[], prop: string): INumberObject => {
  const finalObject: any = {};

  for (const el of arr) {
    if (el[prop] != "" && el[prop] != null) {
      if (finalObject[el[prop]]) {
        finalObject[el[prop]] += 1;
      } else {
        finalObject[el[prop]] = 1;
      }
    }
  }

  return finalObject;
};

export const mapByObjectProp = (arr: any[], prop: string): any => {
  const finalObject: any = {};

  for (const el of arr) {
    try {
      const value = getPropByString(el, prop);

      if (value != null) {
        if (finalObject[value]) {
          finalObject[value].push(el);
        } else {
          finalObject[value] = [el];
        }
      }
    } catch (e) {
      console.log(e);
    }
  }

  return finalObject;
};

export const mapArrayByProp = (arr: any[], prop: string) => {
  const items: any = [];

  for (const el of arr) {
    const value = getPropByString(el, prop);

    if (value != null) {
      const item = items.find((el: any) => el.id === value);
      if (item) {
        item.instances.push(el);
      } else {
        items.push({
          ...el,
          instances: [el],
        });
      }
    }
  }

  return items;
};

export const getProperties = (obj: any, properties: string[]) => {
  const finalObject: any = {};

  for (const prop of properties) {
    if (obj[prop] !== undefined) {
      finalObject[prop] = obj[prop];
    }
  }

  return finalObject;
};

export const cumulAllValues = (obj: any) => {
  let values: any[] = [];

  for (const key in obj) {
    values = [...values, ...obj[key]];
  }

  return values;
};

export const objectToArrayOptions = (obj: any) => {
  const options: any[] = [];

  for (const key in obj) {
    options.push({
      value: key,
      label: obj[key],
    });
  }

  return options;
};
