import { months } from '../constants/common.mjs';

export function generateTrackerLink(operator, trackerType, provider = false) {
  let defaultTrackerFormat = provider
    ? process.env.PROVIDER_TRACKER_LINK_FORMAT_MAIN
    : process.env.TRACKER_LINK_FORMAT_MAIN;
  let trackerFormat = provider
    ? process.env.PROVIDER_TRACKER_LINK_FORMAT_NON_MAIN
    : process.env.TRACKER_LINK_FORMAT_NON_MAIN;

  if (defaultTrackerFormat && trackerFormat) {
    if (operator.type === 'casino') {
      defaultTrackerFormat = defaultTrackerFormat.replace('type,', '');
      trackerFormat = trackerFormat.replace('type,', '');
    }
    const linkFormatArray =
      trackerType === 'main' ? defaultTrackerFormat.split(',') : trackerFormat.split(',');

    const trackerArr = linkFormatArray.map((item) => {
      const customSection = item.match(/\[(.*)\]/);
      if (customSection) {
        const sectionName = customSection.pop();
        return sectionName === 'tracker' ? trackerType : sectionName;
      }

      if(item === 'country') {
        const markets = operator.market.split('_');
        if(markets.length === 2) { 
          return markets[0];
        }
      }
      
      return operator[item];
    });
    return `/${trackerArr.join('/')}`;
  }
}

export function generatePlaceholderString(string = '', translations, data) {
  const date = new Date();
  const day = date.getDate();
  const month = months[date.getMonth()];
  const year = date.getFullYear();
  const regex =
    /\[MONTH\]|\[YEAR\]|\[currentyear\]|\[sitename\]|\[currentmonth\]|\[title\]|\[currentdate\]|\[operator_name]/gi;

  return string.replace(
    regex,
    (match) =>
      ({
        '[MONTH]': (translations && translations[month]) || month,
        '[YEAR]': year,
        '[currentdate]': `${(translations && translations[month]) || month} ${day}, ${year}`,
        '[currentmonth]': (translations && translations[month]) || month,
        '[currentyear]': year,
        '[sitename]': (data && data.siteName) || '',
        '[title]': (data && data.pageTitle) || '',
        '[operator_name]': (data && data.name) || '',
      }[match])
  );
}

export function generateArray(obj) {
  return obj !== null && obj !== undefined ? Object.keys(obj).map((key) => obj[key]) : [];
}
