<template>
  <input ref="file" type="file" name="file" id style="display: none" />
</template>
<script>
import * as fileInfo from "../../utils/file";

export default {
  props: {
    mediaType: String,
  },
  data() {
    return {
      ext: "",
      name: "",
      type: "",
      size: 0,
    };
  },
  mounted() {
    this.$el.addEventListener("change", (e) => {
      if (!window.FileReader) {
        this.$confirm({ content: this.$t("common.uploads.cant_upload") });
        return;
      }

      if (e.target.files.length === 0) {
        this.ext = "";
        this.name = "";
        this.type = "";
        this.size = 0;
        this.dataURL = "";
        return;
      }

      const file = e.target.files[0];

      if (!fileInfo.checkMediaMime(this.mediaType, file.name)) {
        return this.$confirm({
          content: this.$t("common.uploads.not_support", {
            fileType: fileInfo.mediaTypes[this.mediaType],
          }),
        });
      }

      if (!fileInfo.checkSizeLimit(this.mediaType, file.size)) {
        return this.$confirm({
          content: this.$t("common.uploads.not_support", {
            fileType: fileInfo.mediaMaxSize[this.mediaType],
          }),
        });
      }

      const reader = new FileReader();

      reader.readAsDataURL(file);

      reader.onload = (e) => {
        this.dataURL && window.URL.revokeObjectURL(this.dataURL);
        this.name = file.name;
        this.type = file.type;
        this.mime = fileInfo.getMime(file.name);
        this.size = file.size;
        this.dataURL = fileInfo.base64ToDataURL(e.target.result);
        this.$emit("file-change", this, e);
      };

      e.target.value = "";
    });
  },
  methods: {
    click() {
      this.$el.click();
    },
    upload() {},
  },
};
</script>
