<template>
  <v-container>
    <v-snackbar color="error" v-model="alertSnackbar" :timeout="2000">{{alertText}}</v-snackbar>
    <v-row justify="center" align="center" dense class="flex-wrap mb-6">
      <v-col md="3" lg="3">
        <v-card tile>
          <v-card-actions>
            <v-row style="margin:auto" class="justify-center align-center flex-wrap">
              <v-col>
                <v-file-input
                  :messages="uploadMessage"
                  :loading="uploadLoading"
                  @change="fileUploadFunc"
                  type="file"
                  :label="$t('TransliterationRoute.uploadLabel')"
                  accept="application/x-sqlite3"
                ></v-file-input>
              </v-col>
            </v-row>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>

    <v-row justify="center" dense class="flex-wrap mt-6">
      <v-col md="10" cols="12">
        <v-card class="justify-center">
          <v-progress-linear
            :active="TransliterationLoading"
            :indeterminate="TransliterationLoading"
            absolute
            top
            color="cyan lighten-2"
          ></v-progress-linear>
          <v-card-title>
            <strong>{{transliterationdb!=undefined?transliterationdb.length:0}}/{{count}}</strong>
            <v-spacer></v-spacer>
            <v-text-field
              v-model="search"
              append-icon="search"
              :label="$t('DataTableSearch')"
              single-line
              hide-details
              style="width:400px"
              class="flex-grow-0"
            ></v-text-field>
          </v-card-title>
          <v-data-table
            ref="TransliterationTable"
            :headers="headerOfTable"
            :items="itemsOfTable"
            item-key="_id"
            class="elevation-1"
            style="width:100%"
            fixed-header
            disable-sort
            :height="tableHeight"
            disable-pagination
            hide-default-footer
            :search="search"
          ></v-data-table>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>
<script>
import { FilesCollection } from "meteor/ostrio:files";
import TranslitDbUploads from "../../imports/api/collections/translitdbuploads.js";
import TransliterationDb from "../../imports/api/collections/transliterationdb.js";
import { Counts } from "meteor/tmeasday:publish-counts";
export default {
  data() {
    return {
      TransliterationLoading: false,
      limit: 40,
      count: 0,
      search: "",
      tableHeight: "62vh",
      prevLeft: 0,
      uploadLoading: false,
      uploadMessage: "",
      alertSnackbar: false,
      alertText: ""
    };
  }, 
  computed: {
    links() {
      let links = [];
      this.translitdbuploads.forEach(function(fileRef) {
        links.push(TranslitDbUploads.link(fileRef));
      });
      return links;
    },
    itemsOfTable() {
      if (this.transliterationdb && this.transliterationdb.length > 0) {
        let transliterationdbArray = [];
        for (let worklist of this.transliterationdb) {
          let tempWorklist = {};
          for (let prop in worklist) {
            tempWorklist[prop] = JSON.stringify(worklist[prop]);
          }
          transliterationdbArray.push(tempWorklist);
        }
        return transliterationdbArray;
      }
      return [];
    },
    headerOfTable() {
      if (this.transliterationdb && this.transliterationdb.length > 0) {
        let headerNames = [];
        let worklist = this.transliterationdb[0];
        for (let prop in worklist) {
          headerNames.push({
            text: prop,
            value: prop,
            class: "text-center",
            width: 180
          });
        }
        return headerNames;
      }
      return [];
    }
  },
  methods: {
    fileUploadFunc(file) {
      if (file == undefined) {
        this.uploadLoading = false;
        this.uploadMessage = "";
        this.alertText = this.$t("TransliterationRoute.errorInUploading");
        this.alertSnackbar = true;
        return;
      }
      this.uploadLoading = true;
      this.uploadMessage = this.$t("TransliterationRoute.uploadingText");
      let me = this;

      const upload = TranslitDbUploads.insert(
        {
          file: file,
          streams: "dynamic",
          chunkSize: "dynamic"
        },
        false
      );

      upload.on("end", function(error, fileObj) {
        if (error) {
          me.uploadLoading = false;
          me.uploadMessage = "";
          me.alertText = me.$t("TransliterationRoute.wrongFormat");
          me.alertSnackbar = true;
        } else {
          if (fileObj.type != "application/x-sqlite3") {
            me.uploadLoading = false;
            me.uploadMessage = "";
            me.alertText = me.$t("TransliterationRoute.wrongFormat");
            me.alertSnackbar = true;
            return;
          }
          me.limit = 40;
          me.uploadMessage = me.$t("TransliterationRoute.finishUpload");
          Meteor.setTimeout(() => {
            me.uploadMessage = me.$t("TransliterationRoute.dbUpdate");
          }, 500);

          Meteor.call("sqlite2mongo", fileObj.versions.original.path, function(
            err,
            result
          ) {
            if (result == true) {
              me.uploadMessage = me.$t("TransliterationRoute.dbUpdateDone");
              Meteor.setTimeout(() => {
                me.uploadMessage = "";
              }, 500);
              me.uploadLoading = false;
            }
          });
        }
      });
      upload.start();
    },
    onScroll(e) {
      let currentLeft = e.target.scrollLeft;
      if (this.prevLeft != currentLeft) {
        this.prevLeft = currentLeft;
        return;
      }

      let element = this.$refs.TransliterationTable.$el.querySelector(
        ".v-data-table__wrapper"
      );
      let scrollHeight = element.scrollHeight;
      let divHeight = element.clientHeight;
      let scrollerEndPoint = scrollHeight - divHeight;
      let divScrollerTop = e.target.scrollTop;
      if (divScrollerTop === scrollerEndPoint) {
        
        this.count = Counts.get("transliterationCount");
        if (this.transliterationdb.length < this.count) {
          this.limit += 5;
        }
      }
    }
  },
  watch: {
    "$subReady.transliterationdb"(ready) {
      this.TransliterationLoading = !ready;
      if (this.$refs.TransliterationTable) {
        this.$refs.TransliterationTable.$el
          .querySelector(".v-data-table__wrapper")
          .removeEventListener("scroll", this.onScroll);
        this.$refs.TransliterationTable.$el
          .querySelector(".v-data-table__wrapper")
          .addEventListener("scroll", this.onScroll);
      }
    }
  },
  meteor: {
    $subscribe: {
      translitdbuploads: [],
      transliterationdb: function() {
        // this.TransliterationLoading = true;

        return [
          { limit: this.limit }
        ];
      },
      transliterationdbCount: []
    },
    translitdbuploads() {
      return TranslitDbUploads.find({});
    },
    transliterationdb() {
    
      return TransliterationDb.find({}, { sort: { ID: 1 } });
    }
  }
};
</script>