<template>
  <div class="file-item" @click="handleItemClick">
    <div
      class="file-item__icon"
      :style="{ backgroundImage: `url(${getFileIcon(fileName)})` }"
    ></div>
    <div class="file-item__base-info">
      <div class="file-item__name">{{ fileName }}</div>
      <div class="file-item__size">{{ sizeText }}</div>
    </div>
    <div class="file-item__action" v-if="!isDir">
      <slot name="action"></slot>
    </div>
  </div>
</template>

<script>
import { getFileTypeIcon } from "../../utils/filetype.icon";

const KB = 1024;
const MB = 1024 ** 2;
const GB = 1024 ** 3;
const TB = 1024 ** 4;
const PB = 1024 ** 5;

export default {
  name: "BgoFileItem",
  props: {
    isDir: {
      type: Boolean,
      default: false,
    },
    fileName: {
      type: String,
      required: true,
    },
    // File Size, if date type is Number, will be treated in Byte
    size: {
      type: [String, Number],
    },
  },
  computed: {
    sizeText() {
      if (typeof this.size === "string") {
        return this.size;
      } else {
        let text = "";
        if (this.size < KB) {
          text = this.size + "Byte";
        } else if (this.size < MB) {
          text = (this.size / KB).toFixed(2) + "KB";
        } else if (this.size < GB) {
          text = (this.size / MB).toFixed(2) + "MB";
        } else if (this.size < TB) {
          text = (this.size / GB).toFixed(2) + "GB";
        } else if (this.size < PB) {
          text = (this.size / TB).toFixed(2) + "TB";
        } else {
          text = (this.size / PB).toFixed(2) + "PB";
        }

        return text;
      }
    },
  },
  methods: {
    getFileIcon(fileName) {
      return getFileTypeIcon(
        fileName.split(".").slice(-1).join("").toLowerCase()
      );
    },
    handleItemClick(event) {
      this.$emit("click", event);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
