<template>
  <div class="animated fadeInLeft">
    <div class="vh-50 bg-primary"></div>
    <b-row class="mx-0 justify-content-center tree-upload-screen">
      <b-col cols="12" lg="8" xl="6">
        <b-card class="shadow card-height">
          <div class="text-center mb-5">
            <b-card-title class="font-size-2">{{ $t('TreeViewer.Upload.Title') }}</b-card-title>
            <b-card-sub-title>{{ $t('TreeViewer.Upload.SupportText') }}</b-card-sub-title>
          </div>
          <b-form-file
            v-model="sourceFile"
            accept="application/json"
            :placeholder="$t('TreeViewer.Upload.Placeholder')"
            :drop-placeholder="$t('TreeViewer.Upload.Placeholder.DropFile')"
            class="custom-file-upload"
          ></b-form-file>
        </b-card>
      </b-col>
    </b-row>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'Upload',
  data() {
    return {
      sourceFile: {},
    }
  },
  methods: {
    ...mapActions(['getMemberTreeActionGenealogy']),
    readFiles(file) {
      let reader = new FileReader()
      reader.onload = event => {
        //start extracting the data
        try {
          let data = JSON.parse(event.target.result)
          this.loadTreeData(data)
        } catch {
          this.invalidFile()
        }
      }
      reader.readAsText(file) //put file that you wanted to read
    },
    invalidFile() {
      this.sourceFile = null
      this.$swal({
        title: this.$t('TreeViewer.Upload.UploadFile.Invalid.Title'),
        text: this.$t('TreeViewer.Upload.UploadFile.Invalid.Msg'),
        type: 'error',
      })
    },
    loadTreeData(data) {
      this.getMemberTreeActionGenealogy({ external_data_source: data })
      this.$router.push({ name: 'PlacementTreeDiagram' })
    },
  },
  watch: {
    sourceFile(file) {
      if (file !== null) {
        if (file.type === 'application/json') {
          this.readFiles(file)
        } else {
          this.invalidFile()
        }
      }
    },
  },
}
</script>
