import { useTranslation } from "react-i18next"
import { memo } from "react"
import { useEvent } from "@aet/hooks"
import { gql, useLazyQuery } from "~/generated/graphql"
import { BlockButton } from "~/shared/styled"

function download(content: string, mimeType: string, filename: string) {
  const a = document.createElement("a")
  const blob = new Blob([content], { type: mimeType })
  const url = URL.createObjectURL(blob)
  a.setAttribute("href", url)
  a.setAttribute("download", filename)
  a.click()
}

const BACKUP_QUERY = gql<"BackupQuery">`
  query BackupQuery {
    export
  }
`

export const Exporter = memo(() => {
  const { t } = useTranslation()
  const [runBackup] = useLazyQuery(BACKUP_QUERY)

  const onExport = useEvent(async () => {
    const { data } = await runBackup()
    download(JSON.stringify(data!.export), "application/json", "backup.json")
  })

  return <BlockButton onClick={onExport}>{t("import.export")}</BlockButton>
})
