import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import {
  MAX_MEDIA_SIZE_BYTES,
  MAX_MEDIA_SIZE_MB,
  prepareMediaFile,
} from "src/helpers/mediaFile";

export function useMediaFile() {
  const $q = useQuasar();
  const { t } = useI18n();

  const buildMessage = (error) =>
    t(`common.ui.file.errors.${error.code}`, {
      size: error.size,
      max: error.max,
    });

  const prepareFile = async (file, { notify = true } = {}) => {
    const { file: prepared, error, compressed } = await prepareMediaFile(file);

    if (error) {
      const message = buildMessage(error);
      if (notify) {
        $q.notify({ type: "negative", message, timeout: 8000 });
      }
      return { file: null, message };
    }

    if (compressed && notify) {
      $q.notify({
        type: "info",
        message: t("common.ui.file.compressed", { max: MAX_MEDIA_SIZE_MB }),
      });
    }

    return { file: prepared, message: null };
  };

  const prepareFiles = async (files, options = {}) => {
    const accepted = [];

    for (const file of Array.from(files ?? [])) {
      const { file: prepared } = await prepareFile(file, options);
      if (prepared) accepted.push(prepared);
    }

    return accepted;
  };

  return {
    prepareFile,
    prepareFiles,
    maxSizeMB: MAX_MEDIA_SIZE_MB,
    maxSizeBytes: MAX_MEDIA_SIZE_BYTES,
  };
}
