/* eslint-disable no-nested-ternary */
import { generateTrackerLink } from './generators.mjs';

export function getURLParam(param) {
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  return urlParams.get(param);
}

export function getPageTitle(page) {
  const searchquery = typeof window !== 'undefined' ? getURLParam('s') : '';
  if (page.path === 's') {
    return `You searched for ${searchquery} - ${process.env.GATSBY_SITE_NAME}`;
  }
  return page.meta_title;
}

export function getExtraField(extraFields, key, defaultValue) {
  if (extraFields && extraFields[key]) {
    return extraFields[key];
  }
  if (defaultValue) {
    return defaultValue;
  }
  return null;
}

export function getSection(shortCode, pageContext) {
  const page = pageContext && pageContext.page;
  const marketSections = pageContext && pageContext.marketSections;
  // eslint-disable-next-line
  if (!page || !page.hasOwnProperty('sections') || !page.sections.hasOwnProperty(shortCode)) {
    return null;
  }
  // market has priority over page
  if (marketSections[shortCode]) {
    return marketSections[shortCode];
  }
  return page.sections[shortCode] || {};
}

export function textWordsLimit(text, limit = 50) {
  if (!text || typeof text !== 'string') {
    return null;
  }

  const stripped = text.replace(/<[^>]+>/g, '');

  const words = stripped.split(' ');
  if (limit >= words.length) {
    return stripped;
  }
  const truncated = `${words.slice(0, limit).join(' ')}...`;

  return truncated;
}

export function filterImgSrc(src) {
  if (!src) return src;
  return src.includes('wp-content') ? `https://www.norskespilleautomater.com${src}` : src;
}

export function image(filename, width, height, fit = 'cover') {
  if (!filename) {
    return null;
  }
  const cloudFrontUrl = 'https://d3449cb8ihm3k3.cloudfront.net';
  const imageRequest = JSON.stringify({
    bucket: 'assets-srv',
    key: filename,
    edits: {
      resize: {
        width,
        height,
        fit,
        background: {
          r: 255,
          g: 255,
          b: 255,
          alpha: 0,
        },
      },
    },
  });
  return `${cloudFrontUrl}/${Buffer.from(imageRequest).toString('base64')}`;
}

export function getImageFilename(src) {
  const srcArr = src && src.substring(src.lastIndexOf('/') + 1).split('.');
  if (!srcArr.length) {
    return '';
  }

  return srcArr[0];
}

export function getImageExtension(filename) {
  return filename && filename.split('.').pop();
}

export function isBrowserWebpCompatable(feature, callback) {
  const kTestImages = {
    lossy: 'UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA',
    lossless: 'UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==',
    alpha:
      'UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==',
    animation:
      'UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA',
  };
  const img = new Image();
  // eslint-disable-next-line func-names
  img.onload = function () {
    const result = img.width > 0 && img.height > 0;
    callback(feature, result);
  };
  // eslint-disable-next-line func-names
  img.onerror = function () {
    callback(feature, false);
  };
  img.src = `data:image/webp;base64,${kTestImages[feature]}`;
}

export function imagePrettyUrl(filename = 'image.png', width = null, height = null) {
  const extension = getImageExtension(filename);

  const hasFilters = extension !== 'svg' && extension !== 'gif';
  const cdnURL =
    (hasFilters
      ? process.env.IMAGE_CDN_URL
      : process.env.IMAGE_CDN_URL.replace('/filters:format(webp)', '')) ||
    process.env.STORYBOOK_IMAGE_CDN_URL;

  if (width && height && hasFilters) {
    const urlPath = '/fit-in';
    const urlSize = `/${width}x${height}`;

    return `${cdnURL}${urlPath}${urlSize}/${filename}`;
  }

  return `${cdnURL}/${filename}`;
}

export function getPageImage(page) {
  if (page.relation_type === 'operator') {
    if (page.featured_image) {
      return imagePrettyUrl(page.featured_image);
    }
    if (page.relation.default_logo_url || page.relation.standardised_logo_url) {
      return imagePrettyUrl(page.relation.standardised_logo_url || page.relation.default_logo_url);
    }
    return imagePrettyUrl(page.relation.logo_url);
  }

  if (page.relation_type === 'game') {
    if (page.featured_image) {
      return imagePrettyUrl(page.featured_image);
    }
    if (page.relation.thumbnail_filename) {
      return page.relation.thumbnail_filename;
    }
  }

  if (page.relation_type === 'software_provider' && page.relation && page.relation.logo) {
    return page.relation && imagePrettyUrl(page.relation.logo);
  }
  if (page.banner) {
    return imagePrettyUrl(page.banner);
  }
  return null;
}

export function getParameterCaseInsensitive(object, key) {
  const asLowercase = key.toLowerCase();
  return object[Object.keys(object)
    .find(k => k.toLowerCase() === asLowercase)
  ];
}

export function prettyTracker(
  operator,
  trackerType = 'main',
  provider = false,
  pageTemplateName = null
) {
  if (pageTemplateName && operator && operator.links && operator.links[pageTemplateName]) {
    return generateTrackerLink(operator, pageTemplateName, provider);
  }
  
  if (!operator || !operator.short_name || (operator.status && operator.status !== 'active')) {
    return null;
  }

  // if tracker is not main, check if the tracker exists,  if not use main
  if (trackerType !== 'main' && operator.links && getParameterCaseInsensitive(operator.links, trackerType) === undefined) {
    trackerType = 'main';
  }
  
  return generateTrackerLink(operator, trackerType, provider);
}

export function getBonus(name, operator) {
  if (!operator) {
    return null;
  }
  // site data
  if (
    operator.one_liners &&
    // eslint-disable-next-line
    operator.one_liners.hasOwnProperty(name) &&
    operator.one_liners[name].one_liner !== ''
  ) {
    return operator.one_liners[name];
  }
  // market data
  if (
    operator.bonus &&
    operator.bonus.one_liners &&
    // eslint-disable-next-line
    operator.bonus.one_liners.hasOwnProperty(name)
  ) {
    return operator.bonus.one_liners[name] || null;
  }
  return null;
}

export function getGameExtraField(relation, key) {
  if (
    relation &&
    relation.affiliate_games &&
    relation.affiliate_games &&
    relation.affiliate_games.no_no
  ) {
    return relation.affiliate_games.no_no.extra_fields[key] || null;
  }
  return null;
}

export function getSectionExtraField(item, section, key) {
  if (
    item &&
    item.sections &&
    item.sections[section] &&
    item.sections[section].extra_fields &&
    item.sections[section].extra_fields[key]
  ) {
    return item.sections[section].extra_fields[key];
  }
  if (!item && section && section.extra_fields && section.extra_fields[key]) {
    return section.extra_fields[key];
  }
  return null;
}

export function getGameRating(object) {
  // // this might break if a site has multiple markets
  // const firstMarket = object.markets && Object.keys(object.markets)[0];
  // if (object.markets && object.markets[firstMarket]) {
  //   return (
  //     ((object.markets[firstMarket].first_rating
  //       ? Number(object.markets[firstMarket].first_rating)
  //       : 0) +
  //       (object.markets[firstMarket].second_rating
  //         ? Number(object.markets[firstMarket].second_rating)
  //         : 0) +
  //       (object.markets[firstMarket].third_rating
  //         ? Number(object.markets[firstMarket].third_rating)
  //         : 0) +
  //       (object.markets[firstMarket].fourth_rating
  //         ? Number(object.markets[firstMarket].fourth_rating)
  //         : 0)) /
  //     4
  //   );
  // }
  return (
    ((object.first_rating ? Number(object.first_rating) : 0) +
      (object.second_rating ? Number(object.second_rating) : 0) +
      (object.third_rating ? Number(object.third_rating) : 0) +
      (object.fourth_rating ? Number(object.fourth_rating) : 0)) /
    4
  );
}

export function getGameIframe(relation, language = null) {
  if (!relation) {
    return null;
  }
  if (language) {
    if (relation.devices && relation.devices[language] && relation.devices[language].desktop) {
      return relation.devices[language].desktop.url;
    }
    if (relation.devices && relation.devices[language] && relation.devices[language].all) {
      return relation.devices[language].all.url;
    }
  }
  if (relation.devices && relation.devices.en && relation.devices.en.desktop) {
    return relation.devices.en.desktop.url;
  }
  if (relation.devices && relation.devices.en && relation.devices.en.all) {
    return relation.devices.en.all.url;
  }
  if (relation.iframe) {
    return relation.iframe;
  }
  return null;
}

export function isTandcEnabled(extraFields) {
  return (
    extraFields.terms_and_conditions_text_enabled &&
    ((extraFields.terms_and_conditions_text_enabled && extraFields.terms_and_conditions) ||
      (extraFields.terms_and_conditions_link_enabled && extraFields.terms_and_condition_link_text))
  );
}

export function getUrl(path) {
  if (!path) {
    return '';
  }

  if (path === '/') {
    return process.env.GATSBY_SITE_URL;
  }

  return `${process.env.GATSBY_SITE_URL}${path.replace(/^\//, '')}`;
}

export function getLanguage(language) {
  if (language === 'no') return 'nb-NO';
  return language || 'en';
}

export function copyrightText() {
  const today = new Date();
  // add a function to get the site name and start Year, currently it is not available
  const years = `2009-${today.getFullYear()}`;
  return `Copyright © ${years}`;
}

export function getFirstModuleByName(section, moduleName) {
  if (
    section &&
    section.modules &&
    section.modules.length > 0 &&
    section.modules[0].name === moduleName
  ) {
    return section.modules[0];
  }
  return null;
}

export function translate(translations, key, defaultValue = '') {
  // eslint-disable-next-line
  if (translations && translations.hasOwnProperty(key)) {
    return translations[key];
  }
  return defaultValue;
}

// This part of the code, help us to add operator related to the page as the first item in the comparison table automatically
// example: if we are on the operator review page(Rizk) that should be first in the comparison table
// First, we check if we have that item in the array, if that item is in the array, we check its position
// If the item isn't in the array we will add it automatically
export function shiftFirstOperator(pageId, module, pagesMappedById) {
  let index = null;
  // check if exist that element in array
  const checkIfExistElement = module.items.find((item, i) => {
    if (item.id === pageId) {
      index = i;
      if (index > 0) {
        // eslint-disable-next-line no-nested-ternary
        module.items.sort((x, y) => (x.id === pageId ? -1 : y.id === pageId ? 1 : 0));
      }
      return true;
    }
    return false;
  });
  if (!checkIfExistElement) {
    // eslint-disable-next-line no-unused-expressions
    if (pagesMappedById[pageId] && pagesMappedById[pageId].relation_type === 'operator') {
      module.items.unshift(pagesMappedById[pageId]);
    }
  }
}

export const getModuleTitle = (module, page) => {
  if (page && page.relation && page.relation_type === 'operator') {
    return (
      module.module_title && module.module_title.replace('[operator_name]', page.relation.name)
    );
  }

  return module.module_title;
};

export const getRoundMinutes = (time) => {
  const [minutes, seconds] = time.split(':');
  const value = seconds > 30 ? Number(minutes) + 1 : Number(minutes);
  return value === 0 ? 1 : value;
};

export function getAltText(imageObject, defaultAlt = 'missing alt') {
  return imageObject && imageObject.alt ? imageObject.alt : defaultAlt;
}

export function updateArrayTranslations(array, keysArray, translations) {
  if (array && array.length > 0 && keysArray && keysArray.length > 0) {
    array.forEach((elm, index) => {
      array[index] = translate(translations, keysArray[index], elm);
    });

    return array;
  }
}

export function getObjectValue(obj, path) {
  if (!path) return obj;
  const properties = path.split('.');
  return getObjectValue(obj[properties.shift()], properties.join('.'));
}

export function getBonusData(item, tracker, splitBy = '+') {
  const isInoperative = item?.status === 'inactive';
  let oneLiner = getBonus(tracker, item);
  if (!oneLiner) {
    oneLiner = getBonus('main', item);
  }
  if (!oneLiner) {
    return null;
  }

  let mainLine = null;
  let secondLine = null;
  if (oneLiner?.one_liner !== null && oneLiner?.one_liner.includes(splitBy)) {
    mainLine = oneLiner?.one_liner.split(splitBy)[0];
    secondLine = oneLiner?.one_liner.split(splitBy)[1];
  } else {
    mainLine = oneLiner?.one_liner;
  }
  return {
    isInoperative,
    mainLine,
    secondLine
  }
}