import { notifyError, notifySuccess } from '.';

export async function copyJsonToClipboard(content: Record<string, any> | string) {
  let text: string;
  if (typeof content !== 'string') {
    try {
      text = JSON.stringify(content, null, 2);
    } catch (error) {
      notifyError(error, 'Error al convertir el objeto a JSON');
      return;
    }
  } else {
    text = content;
  }
  navigator.clipboard
    .writeText(text)
    .then(() => {
      notifySuccess('JSON copiado al portapapeles');
    })
    .catch(notifyError);
}

export async function getJsonFromClipboard() {
  return navigator.clipboard
    .readText()
    .then((text) => {
      try {
        const json = JSON.parse(text);
        return json;
      } catch (error) {
        notifyError(null, 'El texto copiado no es un JSON válido');
      }
    })
    .catch(notifyError);
}
