import axios from 'axios';
/**
 *
 * @param {*} name name is the string to be shortened
 * @param {*} length length is the maximum length before a text is shortened.
 */

export const nameShortner = (name, length) => {
  if (name && length) {
    const splitName = name.split('');

    if (splitName.length > length) {
      return `${splitName.splice(0, length).join('')}...`;
    } else {
      return name;
    }
  } else {
    return null;
  }
};
/**
 * @function validateEmail
 * @param {*} email
 * @description check if an input is a valid email address
 */

export const validateEmail = email => {
  const re = /\S+@\S+\.\S+/;
  return re.test(email);
};
/**
 * @function: getNameInitials
 * @param {*} name
 * @description: get the first letters in a name
 */

export const getNameInitials = name => {
  if (name) {
    const matches = name.match(/\b(\w)/g);
    return matches;
  } else {
    return null;
  }
};
export const getUploadUrl = async file => {
  const data = new FormData();
  data.append('files', file);
  data.append('folder', 'admin-profile');
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  };
  const uploadData = await axios.post('/files', data, config);
  return uploadData;
};
/**
 *
 * @param {*} x a number to add commas to
 */

export const numberWithCommas = x => {
  if (x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  } else {
    return 0;
  }
};
export const numbersOnly = value => {
  const compare = /^[0-9]{1,15}$/g;

  if (value && value.length > 0) {
    if (value.match(compare)) {
      return true;
    } else {
      return false;
    }
  }
};
/**
 * @description: the condition that determines if an element will be displayed or not
 * @param {*} elementDetails
 */

export const toBeDisplayed = (
  elementDetails,
  elementsWithLogics,
  pages,
  activePage,
  resetAction
) => {
  const allElements = pages ? pages.flat() : [];
  const elementId = elementDetails.unique_id;
  let ruleSource = '';
  let currentRule = {};
  let expectedValue = '';
  let multiExpectedValues = []; // let condition = '';

  let action = '';
  let answer = '';
  let meetCondition = true;

  if (elementDetails.hidden === true) {
    meetCondition = false;
  }

  if (elementsWithLogics) {
    elementsWithLogics.map(element => {
      if (element.logics.length > 0) {
        element.logics.map(logic => {
          let targets = [];

          if (logic.targets && logic.targets.length > 0) {
            if (logic.targets[0].value) {
              // check if the logic target is an array of objects (Useform format)
              Object.keys(logic.targets).map(x =>
                targets.push(logic.targets[x].value)
              );
            } else {
              targets = logic.targets; // if targets is just an array of strings (Databeaver v3 support)
            }

            if (targets.includes(elementId)) {
              multiExpectedValues.push(logic.value);
              currentRule = element;
              ruleSource = element.unique_id;
              expectedValue = logic.value; // condition = logic.condition;

              action = logic.action;
            } else if (logic.target && logic.target === elementId) {
              multiExpectedValues.push(logic.value);
              currentRule = element;
              ruleSource = element.unique_id;
              expectedValue = logic.value; // condition = logic.condition;

              action = logic.action;
            }

            allElements.map(elem => {
              if (currentRule !== undefined && elem.id === ruleSource) {
                answer = elem.answer;

                if (
                  answer === expectedValue ||
                  multiExpectedValues.includes(answer) ||
                  answer.includes(expectedValue) ||
                  multiExpectedValues.some(x => answer.includes(x))
                ) {
                  if (action === 'show') {
                    meetCondition = true;
                  } else if (action === 'hide') {
                    meetCondition = false;
                  }
                }
              }
            });
          }
        });
      }
    });
  }

  if (
    answer === expectedValue ||
    multiExpectedValues.includes(answer) ||
    answer.includes(expectedValue) ||
    multiExpectedValues.some(x => answer.includes(x))
  ) {
    if (meetCondition === true) {
      return true;
    }
  } else {
    resetAction(elementDetails.unique_id, activePage);
    multiExpectedValues = [];
    answer = '';

    if (meetCondition === false) {
      return false;
    }
  }
};
