<template>
  <div v-bind:class="[componentClass]">
    <ul class="c-files-list" v-if="filesCount > 0">
      <li v-for="(file, index) in files" :key="index" 
        v-bind:class="{ 'c-file': true, 'c-upload-error': file._status === fileState.error, 'c-upload-succes': file._status === fileState.uploaded }">
        <slot v-if="$scopedSlots.value" name="file" v-bind:file="file"></slot>
        <template v-else>
          <div class="c-file-ext">{{ file.ext }}</div>
          <div class="c-file-container">
            <div class="c-file-info">
              <div>
                <span class="c-file-name">{{ file.orginalFileName }}</span>
                <span class="c-file-size">{{ fV(file.size, 'bytes') }}</span>
              </div>
              <button class="c-file-remove" @click="removeFile(file)"></button>
            </div>
            <div
              class="c-file-progress"
              v-if="file._status !== fileState.added"
            >
              <div class="c-progress-bar" :style="{'width': file._progress + '%'}"></div>
            </div>
          </div>
        </template>
      </li>
    </ul>
    <input type="file" name="file" id="file" :multiple="multiple" v-on:change="filesChange($event.target.files)" />
    <label class="c-btn-add-files" for="file">{{ multiple ? 'Dodaj pliki' : 'Dodaj plik' }}</label>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import base from "./c-base";
import dataSetUtils from "../classes/dataSetUtils";

const props = {
  multiple: {
    type: Boolean,
    default: false
  }
};
export default {
  extends: base,
  data: function() {
    return {
      componentClass: "c-upload-files"
    };
  },
  props,
  computed: {
    ...mapGetters("csAppWindowsUtils", [
      "getDataSetFiles",
      "getDataSetFilesCount"
    ]),
    files: function() {
      return this.getDataSetFiles(this.dataSet);
    },
    filesCount: function() {
      return this.getDataSetFilesCount(this.dataSet);
    },
    fileState: function() {
      return dataSetUtils.fileState;
    }
  },
  methods: {
    ...mapActions("csAppWindowsUtils", ["addFile", "deleteFile", "putFile", "deleteAllFiles"]),
    removeFile: function(file) {
      this.deleteFile({
        dataSet: this.dataSet,
        file: file
      });
    },
    filesChange: async function(files) {
      if (!this.multiple)
        await this.deleteAllFiles({dataSet: this.dataSet})
      files.forEach(file => {
        this.addFile({
          dataSet: this.dataSet,
          file: file
        });
      });
    },
    uploadFile: function(file) {
      this.putFile({
        file: file
      });
    }
  }
};
</script>
