<template>
  <div :class="`flex h-full ${isCol ? '' : 'flex-col'}`">
    <div class="flex items-center justify-between">
      <div class="flex items-center">
        <!-- label of input field -->
        <label class="block text-sm font-medium text-gray-900">{{
          label
        }}</label>
        <!-- asterisk sign to render if field is required -->
        <p v-if="isRequired" class="ml-1 text-red-600">*</p>
      </div>
      <label v-if="!isUploaded" class="text-sm text-gray-500">
        {{ hint }}
      </label>
    </div>
    <button
      type="button"
      class="inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
      @click="initFilestack()"
      :id="id"
      v-if="displayMode == 'overlay' && icon"
    >
      <c-icon
        :type="icon.type"
        :class="icon.class"
        :name="icon.name"
        :viewBox="icon.viewBox"
      ></c-icon>
      {{ buttonText }}
    </button>
    <button
      type="button"
      class="mt-1.5 flex h-full w-auto items-center justify-center rounded-lg border-2 border-dashed border-gray-300 px-9 py-14 text-center hover:border-gray-400 focus:outline-none"
      @click="initFilestack()"
      :id="id"
      v-if="displayMode == 'overlay' && !icon && !isAvatar && !isIconBtn"
    >
      <c-icon
        name="arrow-up"
        type="solid"
        class="mr-1 h-5 w-5 flex-none text-indigo-600"
        viewBox="0 0 20 20"
      ></c-icon>
      <span class="text-sm font-medium text-indigo-900"> Upload </span>
    </button>
    <button
      type="button"
      class="group rounded-full p-2 text-gray-400 hover:bg-gray-200 hover:text-gray-500"
      @click="initFilestack()"
      :id="id"
      v-if="displayMode == 'overlay' && !icon && !isAvatar && isIconBtn"
    >
      <c-icon
        :name="isIconBtnName"
        :type="iconBtnType"
        class="h-5 w-5 flex-none text-gray-400 group-hover:text-gray-500"
        viewBox="0 0 20 20"
        cursorType="cursor-pointer"
      ></c-icon>
    </button>
    <div
      class="relative hidden h-full w-full overflow-hidden rounded-full lg:block"
      @click="initFilestack()"
      :id="id"
      v-if="displayMode == 'overlay' && !icon && isAvatar"
    >
      <img
        v-if="imageUrl"
        class="relative h-full w-full rounded-full object-cover"
        :src="imageUrl"
      />
      <c-avatar
        v-else
        size="very large"
        :nameInitials="shortName"
        :isDynamicallyColored="coloredAvatars"
        :rounded="true"
      ></c-avatar>
      <label
        class="absolute inset-0 flex h-full w-full cursor-pointer items-center justify-center bg-gray-900 bg-opacity-75 text-sm font-medium text-white opacity-0 focus-within:opacity-100 hover:opacity-100"
      >
        <c-icon
          v-if="openIcon"
          :name="openIcon.name"
          :type="openIcon.type"
          :class="openIcon.class"
        ></c-icon>
        <span>{{ uploadText }}</span>
        <span class="sr-only"> user photo</span>
      </label>
    </div>
    <div :class="filestackClasses" :id="filestackId"></div>
    <p v-if="!isValidate" class="mt-2 text-sm text-red-600">
      {{ errorMessage }}
    </p>
    <!-- description about the input field -->
    <p v-if="helpText && isValidate == true" class="mt-2 text-sm text-gray-500">
      {{ helpText }}
    </p>
  </div>
</template>

<script>
import * as filestack from "filestack-js";
import CIcon from "../CIcon/CIcon.vue";
import CAvatar from "../CAvatar/CAvatar.vue";

export default {
  name: "CUpload",
  components: {
    CIcon,
    CAvatar,
  },
  props: {
    id: {
      type: String,
    },
    buttonText: {
      type: String,
      default: "Upload",
    },
    isAvatar: {
      type: Boolean,
      default: false,
    },
    isIconBtn: {
      type: Boolean,
      default: false,
    },
    isIconBtnName: {
      type: String,
      default: "attachment-solid",
    },
    iconBtnType: {
      type: String,
      default: "solid",
    },
    shortName: {
      type: String,
    },
    imageUrl: {
      type: String,
      default: "",
    },
    icon: {
      type: Object,
    },
    fileSize: {
      type: String,
    },
    filestackId: {
      type: String,
      default: "filestack-uploader",
    },
    openIcon: {
      type: Object,
    },
    uploadText: {
      type: String,
      default: "Change",
    },
    hint: {
      type: String,
      default: "",
    },
    helpText: {
      type: String,
    },
    label: {
      type: String,
      default: "",
    },
    isValidate: { type: Boolean },
    errorMessage: {
      type: String,
    },
    filestackApiKey: {
      type: String,
      default: "",
    },
    filestackClasses: {
      type: String,
      default: "w-96 h-96",
    },
    url: {
      type: String,
    },
    maxFiles: {
      type: Number,
      default: 1,
    },
    onUploadSuccess: {
      type: Function,
    },
    aspectRatio: {
      type: Number,
      default: null,
    },
    onUploadOpen: {
      type: Function,
    },
    displayMode: {
      type: String,
      default: "inline",
    },
    isUploaded: {
      type: Boolean,
      default: false,
    },
    isCircle: {
      type: Boolean,
      default: false,
    },
    coloredAvatars: {
      type: Boolean,
      default: false,
    },
    uploadSources: {
      type: Array,
      default: () => ["local_file_system", "unsplash"],
    },
    isRequired: {
      type: Boolean,
    },
    isCol: {
      type: Boolean,
    },
    disableTransformer: {
      type: Boolean,
      default: false,
    },
    maxSize: {
      type: Number,
      default: null,
    },
    fileTypes: {
      type: Array,
      default: () => [],
    },
    policy: {
      type: String,
      default: "",
    },
    signature: {
      type: String,
      default: "",
    },
    hasSecureInitialisation: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {};
  },
  methods: {
    initFilestack() {
      if (this.hasSecureInitialisation && !this.policy.length) {
        if (this.displayMode == "overlay") {
          this.$emit("fetchPolicyDetails");
        }
        return;
      }
      const client = this.hasSecureInitialisation
        ? filestack.init(this.filestackApiKey, {
            security: {
              policy: this.policy,
              signature: this.signature,
            },
          })
        : filestack.init(this.filestackApiKey);

      const options = {
        displayMode: this.displayMode,
        container: `#${this.filestackId}`,
        uploadInBackground: false,
        maxFiles: this.maxFiles,
        onOpen: (param) => this.$emit("onUploadOpen", param, "open"),
        onClose: (param) => this.$emit("onUploadOpen", param, "close"),
        onUploadDone: (res) => this.$emit("filestack-uploaded", res),
        fromSources: this.uploadSources,
        disableTransformer: this.disableTransformer,
        transformations: {
          crop: {
            aspectRatio: this.aspectRatio ? this.aspectRatio : 0,
            force: this.aspectRatio ? true : false,
          },
          circle: this.isCircle,
        },
      };
      if (this.maxSize) {
        options["maxSize"] = this.maxSize;
      }
      if (this.fileTypes && this.fileTypes.length > 0) {
        options["accept"] = this.fileTypes;
      }
      const picker = client.picker(options);
      picker.open();
    },
  },
  computed: {
    errorClasses() {
      return {
        "border-red-300 text-red-900 placeholder-red-300 focus:ring-red-500 focus:border-red-500":
          this.isValidate == false,
        "border-gray-300 border-dashed": this.isValidate == true,
      };
    },
  },
  watch: {
    policy: {
      handler(newVal, oldVal) {
        if (
          this.hasSecureInitialisation &&
          newVal.length &&
          newVal !== oldVal
        ) {
          this.initFilestack();
        }
      },
    },
  },
  mounted() {
    if (this.displayMode == "inline") {
      this.initFilestack();
    }
  },
};
</script>

<style></style>
