import { Caption } from '@/models/caption.model';
import { StatusType } from '..';
import { RouteLocationRaw } from 'vue-router';

export const searchString = (item: any, searchText: any): boolean => {
  return (
    !isEmptyStringOrNotDefined(item) &&
    searchText !== null &&
    searchText !== undefined &&
    sanitizeString(item).includes(sanitizeString(searchText))
  );
};

export const getValueByPath = (obj: any, path: string) => {
  if (path === '' || path === '.') {
    return obj;
  }
  return path.split('.').reduce((acc, key) => acc?.[key], obj);
};

export const isEmptyStringOrNotDefined = (value: any): boolean => {
  return ['', null, undefined].includes(value);
};

export const isExternalLink = (link: string | RouteLocationRaw | null) =>
  !!link && typeof link === 'string' && (link as string).startsWith('http');

export const sanitizeString = (str: any): string => {
  if (!str) {
    return '';
  }
  return str
    .toString()
    .toLowerCase()
    .normalize('NFD')
    .replace(/\p{Diacritic}/gu, '');
};

export const sanitizeHtml = (html: string) => {
  const allowedTags = [
    'b',
    'i',
    'em',
    'strong',
    'a',
    'p',
    'ul',
    'li',
    'ol',
    'span',
  ]; // Liste des balises autorisées
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;

  // Parcourir tous les enfants de l'élément temporaire
  const elements = tempDiv.querySelectorAll('*');
  elements.forEach((el) => {
    // Supprimer les balises non autorisées
    if (!allowedTags.includes(el.tagName.toLowerCase())) {
      el.remove();
    } else {
      // Nettoyer les attributs dangereux pour les balises autorisées
      Array.from(el.attributes).forEach((attr) => {
        const attrName = attr.name.toLowerCase();
        if (attrName.startsWith('on') || attrName === 'style') {
          el.removeAttribute(attrName); // Supprime les événements inline et les styles
        } else if (attrName === 'href' || attrName === 'src') {
          // Valider les URLs (interdire "javascript:" et autres schémas dangereux)
          if (attr.value.toLowerCase().startsWith('javascript:')) {
            el.removeAttribute(attrName);
          }
        }
      });
    }
  });
  return tempDiv.innerHTML; // Renvoie le HTML nettoyé
};

export const convertStringToCaption = (caption: string | Caption): Caption => {
  return typeof caption !== 'string'
    ? caption
    : { label: caption, mode: StatusType.Default };
};
