import FileSaver from 'file-saver';
import { downloadJson } from './downloadJson';

/**
 * A function that saves a string into a downloadable file
 * The download will have the extension specified or default to tx
 * The download and will start automatically
 * @param content string contents to be saved in the file
 * @param extension optional the extension of the file to be saved, if not specified, it will default to txt
 * @param filename optional the name of the file to be saved, if not specified, it will default to the current date
 */
export const saveContentAs = (
  content: string,
  filename?: string,
  extension?: string
) => {
  if (extension === 'json') {
    downloadJson(content, filename);
  }
  const blob = new Blob([content], {
    type: 'text/plain;charset=utf-8'
  });
  const date = new Date().getTime();
  FileSaver.saveAs(
    blob,
    `${filename}.${extension || 'txt'}` || `${date}.${extension}`
  );
};
