<template>
  <transition appear enter-active-class="animated slideInRight" leave-active-class="hidden">
    <div class="q-pa-sm">
      <div class="text-h5 q-pb-md">General Information</div>
      <q-card>
        <q-card-section>
          <div class="q-pa-md flex flex-center column">
            <div
              class="q-uploader column no-wrap q-uploader--bordered q-uploader--square no-border-radius q-uploader--flat no-shadow"
              style="max-width: 300px;"
            >
              <q-file
                :value="files"
                @input="updateFiles"
                label="Pick files"
                outlined
                multiple
                :clearable="!isUploading"
                style="max-width: 400px"
              >
                <template v-slot:file="{ index, file }">
                  <q-chip
                    class="full-width q-my-xs"
                    :removable="isUploading && uploadProgress[index].percent < 1"
                    square
                    @remove="cancelFile(index)"
                  >
                    <q-linear-progress
                      class="absolute-full full-height"
                      :value="uploadProgress[index].percent"
                      :color="uploadProgress[index].color"
                      track-color="grey-2"
                    />

                    <q-avatar>
                      <q-icon :name="uploadProgress[index].icon" />
                    </q-avatar>

                    <div class="ellipsis relative-position">{{ file.name }}</div>

                    <q-tooltip>{{ file.name }}</q-tooltip>
                  </q-chip>
                </template>

                <template v-slot:after v-if="canUpload">
                  <q-btn
                    color="primary"
                    dense
                    icon="cloud_upload"
                    round
                    @click="upload"
                    :disable="!canUpload"
                    :loading="isUploading"
                  />
                </template>
              </q-file>
              <div class="q-uploader__list scroll" style="overflow: hidden;" v-if="img_preview">
                <div
                  class="q-uploader__file relative-position q-uploader__file--img"
                  :style="img_preview"
                >
                  <div class="q-uploader__file-header row flex-center no-wrap">
                    <div class="q-uploader__file-header-content col">
                      <div class="q-uploader__title">{{imageName}}</div>
                    </div>
                    <button
                      tabindex="0"
                      type="button"
                      role="button"
                      class="q-btn q-btn-item non-selectable no-outline q-btn--flat q-btn--round q-btn--actionable q-focusable q-hoverable q-btn--wrap q-btn--dense"
                    >
                      <span class="q-focus-helper"></span>
                      <span class="q-btn__wrapper col row q-anchor--skip">
                        <span
                          class="q-btn__content text-center col items-center q-anchor--skip justify-center row"
                        >
                          <svg
                            aria-hidden="true"
                            role="img"
                            focusable="false"
                            viewBox="0 0 24 24"
                            class="q-icon notranslate"
                            @click="removeFile()"
                          >
                            <path
                              d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"
                            />
                          </svg>
                        </span>
                      </span>
                    </button>
                  </div>
                </div>
              </div>
            </div>
            <div
              class="text-subtitle2 text-thin q-ma-md grey-4"
            >Please only upload your clear facial image.</div>
          </div>
        </q-card-section>
        <q-card-section>
          <div class="profile-img-wrapper">
            <q-img transition="slide-right" class="profile-img-round"  :src="authUserImageUrlMediumSize" />
          </div>
        </q-card-section>
        <q-card-section>
          <div class="row">
            <div class="col-6 col-md-6 col-xs-12 q-pa-md row">
              <div class="text-body1 text-bold text-grey-9">Name:</div>
              <div class="text-body1 text-grey-9 q-pl-md">{{fullName}}</div>
            </div>
            <div class="col-6 col-md-6 col-xs-12 q-pa-md row">
              <div class="text-body1 text-bold text-grey-9">Email:</div>
              <div class="text-body1 text-grey-9 q-pl-md">{{authUser.email}}</div>
            </div>
          </div>
        </q-card-section>
      </q-card>
    </div>
  </transition>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      files: null,
      uploadProgress: [],
      uploading: null,
      img_preview: "",
    };
  },
  computed: {
    ...mapGetters("auth", ["authUser", "authUserImageUrlMediumSize"]),
    fullName() {
      return this.authUser.fname + " " + this.authUser.lname;
    },
    uploadUrl() {
      return this.baseUrl + "api/upload-user-profile-image";
    },
    isUploading() {
      return this.uploading !== null;
    },

    canUpload() {
      return this.files !== null;
    },
    imageName() {
      if (this.files && this.files.length > 0) {
        return this.files[0].name;
      }
      return "";
    },
  },
  methods: {
    removeFile() {
      this.files = null;
      this.img_preview = null;
    },
    cancelFile(index) {
      this.uploadProgress[index] = {
        ...this.uploadProgress[index],
        error: true,
        color: "orange-2",
      };
      this.img_preview = "";
    },

    updateFiles(files) {
      this.files = files;
      this.uploadProgress = (files || []).map((file) => ({
        error: false,
        color: "green-2",
        percent: 0,
        icon:
          file.type.indexOf("video/") === 0
            ? "movie"
            : file.type.indexOf("image/") === 0
            ? "photo"
            : file.type.indexOf("audio/") === 0
            ? "audiotrack"
            : "insert_drive_file",
      }));
      if (files) {
        this.createImage(files[0]);
      } else {
        this.img_preview = null;
      }
    },
    createImage(file) {
      if (file == undefined) {
        return;
      }
      let reader = new FileReader();
      let vm = this;
      reader.onload = (e) => {
        vm.img_preview = `background-image:url(${e.target.result})`;
      };
      reader.readAsDataURL(file);
    },

    upload() {
      let formData = new FormData();
      formData.append("image", this.files[0]);
      const config = {
        headers: { "content-type": "multipart/form-data" },
        onUploadProgress: function (progressEvent) {
          let percent =
            parseFloat(
              Math.round((progressEvent.loaded * 100) / progressEvent.total)
            ) / 100;
          this.uploadProgress = this.uploadProgress.map((p) => ({
            ...p,
            error: false,
            color: "green-2",
            percent: percent,
          }));
          if (percent == 1) {
            this.uploading = null;
          } else {
            this.uploading = percent;
          }
        }.bind(this),
      };

      axios
        .post("/upload-user-profile-image", formData, config)
        .then((res) => {
          this.$store.commit('auth/UPDATE_IMAGE',res.data.image);
          this.$q.notify({
            message: "Upload Success",
            type: "success-notify",
            caption: res.data.msg,
          });
        })
        .catch((e) => {
          this.uploadProgress = this.uploadProgress.map((p) => ({
            ...p,
            error: true,
            color: "red-2",
            percent: p.percent,
          }));
          this.$q.notify({
            message: "Failed",
            type: "error-notify",
            caption: "Sorry!! Image Upload Failed.Please try again later.",
          });
        });
    },

    __updateUploadProgress() {
      let done = true;

      this.uploadProgress = this.uploadProgress.map((progress) => {
        if (progress.percent === 1 || progress.error === true) {
          return progress;
        }

        const percent = Math.min(1, progress.percent + Math.random() / 10);
        const error = percent < 1 && Math.random() > 0.95;

        if (error === false && percent < 1 && done === true) {
          done = false;
        }

        return {
          ...progress,
          error,
          color: error === true ? "red-2" : "green-2",
          percent,
        };
      });

      this.uploading =
        done !== true ? setTimeout(this.__updateUploadProgress, 300) : null;
    },
  },
};
</script>

<style lang="css" scoped>
.profile-img-wrapper{
  display: flex;
  justify-content: center;
  align-items: center;
}
.profile-img-round{
  width:10%;
  border-radius: 50%;
}
.q-uploader__file--img {
  height: 300px !important;
  min-width: 200px !important;
}

.my-image {
  width: 100%;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin: auto;
}

@media only screen and (min-width: 0px) and (max-width: 900px) {
}
</style>
