import { remark } from 'remark';
import html from 'remark-html';
import sanitizeHtml from 'sanitize-html'

export function formatDateToMonthDayYear(date: Date): string {
  return date.toLocaleDateString("en-US", {
    month: "long",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "numeric",
    timeZoneName: "short",
  });
}

export async function markdownToHtml(markdown: string): Promise<string> {

  const result = await remark().use(html).process(markdown)
  const sanitizedHtml = sanitizeHtml(result.toString(), {
    allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'code', 'pre']),
    allowedAttributes: {
      ...sanitizeHtml.defaults.allowedAttributes,
      img: ['src', 'alt'],
    },
  })
  if(sanitizedHtml == ""){
    //Already html
    return markdown
  }
  return sanitizedHtml
}

export function encodeId(documentId: string): string {
  const salt = "salty_aff"
  return Buffer.from(documentId + salt).toString('base64')
}

export function decodeId(encodedId: string): string {
  const salt = "salty_aff"
  return Buffer.from(encodedId, 'base64').toString().replace(salt, '')
}