import { CREATIVES } from "../../../v2Containers/App/constants";

const creativeDetails = ({
  name,
  id,
  channel,
  videoAdded,
  imageAdded,
  stickersAdded,
  timeTaken,
  content,
  mode
}) => {
  const parsedObj = {
    name,
    id,
    creationSource: CREATIVES,
    channel,
    timeTaken,
    isLabelsUsed: isLabelsUsed(content),
    mode,
    imageAdded,
    videoAdded,
    stickersAdded
  };
  window.dataLayer.push({
    creativeDetails: parsedObj,
    event: 'creativeDetails',
  });
};

const isLabelsUsed = (content = '') => {
  const tagRegex = /{{[(A-Z\w+(\s\w+)*$\(\)@!#$%^&*~.,/\\]+}}/g; // eslint-disable-line no-useless-escape
  const isContentString= typeof content === "string";
  if(isContentString){
    content = content.replaceAll('{{optout}}', '');
    content = content.replaceAll('{{unsubscribe}}', '');
  }
  
  const tags = [...content.matchAll(tagRegex)];
  return !!tags.length;
};

/**
 * If replaceAll() String method is unsupported in Browsers
 */
if(!String.prototype.replaceAll){
  /**
   * 
   * @param {String} search 
   * @param {String} replacement 
   * @returns {String} a string replacing all occurances of 'search' with 'replacement'
   */
  String.prototype.replaceAll = function(search,replacement){
    var str = this.valueOf();
    const regularExp = new RegExp(search, 'g');
    return str.replace(regularExp, replacement);
  }
}

export default creativeDetails;
