<template>
  <div>
    <el-dialog
      :title="$t('dams.pcUpload')"
      width="80%"
      :visible.sync="showUploadPc"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      @closed="onPcClosed"
    >
      <DamsUpload :ratio="ratio" @uploaded="uploaded" />
    </el-dialog>

    <el-dialog
      :title="$t('dams.pcDams')"
      width="80%"
      class="dams-dialog"
      :visible.sync="showUploadDams"
      :destroy-on-close="true"
      @closed="onDamsClosed"
    >
      <DamsStructure
        v-if="showUploadDams"
        ref="damsUploadRef"
        :ratio="ratio"
        :singleSelect="true"
        :allowFileType="allowFileType"
        :edit="false"
      />
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :disabled="getChooseDisabled"
          @click="onChooseDamsItem"
        >
          {{ $t("general.choose") }}
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
      width="60%"
      :title="$t('general.preview')"
      :visible.sync="showPreview"
      :destroy-on-close="true"
      append-to-body
      @closed="onPreviewClosed"
    >
      <div class="d-flex justify-content-center align-items-center">
        <el-image :src="selectedPreviewUrl" class="animated fadeIn"></el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import DamsUpload from "./dams-upload.vue";
import DamsStructure from "./dams-structure.vue";
import { DamsItem } from "../../model/dams/dams-item.model";
import { Subscription } from "rxjs";
import { DamsSubscription } from "../../subscription/dams";
import { damsItemSelect } from "../../utils/dams-output";
import { calculateRatio } from "../../utils/calculate-ratio";

@Component({
  name: "DamsKit",
  components: {
    DamsUpload,
    DamsStructure,
  },
})
export default class extends Vue {
  @Prop() ratio!: any;
  @Prop({ default: false }) onDams!: boolean;
  @Prop({ default: false }) onPc!: boolean;
  @Prop() onPreview!: string;
  @Prop({ default: () => [] }) allowFileType!: Array<
    "" | "VIDEO" | "IMAGE" | "PDF" | "AUDIO"
  >;

  showUploadDams = false;
  showUploadPc = false;
  showPreview = false;

  selectedPreviewUrl = "";

  selectedItem: DamsItem = new DamsItem();
  private onSelectFolderSub: Subscription = new Subscription();

  created() {
    this.onSelectFolderSub = DamsSubscription.getDamsState().subscribe(
      (result: any) => {
        // Prevent changing the selected item if ctrl is detected
        if (!this.selectedItem.url || !Vue.prototype.$keyPresses.Control) {
          this.selected(damsItemSelect(result));
        }
      }
    );
  }

  beforeDestroy() {
    if (this.onSelectFolderSub) {
      this.onSelectFolderSub.unsubscribe();
    }
  }

  @Watch("onPc")
  onPcChange() {
    this.showUploadPc = this.onPc;
  }

  @Watch("onDams")
  onDamsChange() {
    this.showUploadDams = this.onDams;
    setTimeout(() => {
      this.getDamsUploadRef("init");
    });
  }

  @Watch("onPreview")
  onPreviewChange(url: string) {
    if (url) {
      this.selectedPreviewUrl = url;
      this.showPreview = true;
    }
  }

  onPcClosed() {
    this.$emit("onPcClosed", this.showUploadPc);
  }

  onDamsClosed() {
    this.$emit("onDamsClosed", this.showUploadDams);
  }

  onPreviewClosed() {
    this.$emit("onPreviewClosed");
  }

  selected(item: DamsItem) {
    this.selectedItem = item;
  }

  get getChooseDisabled() {
    let disabled = true;
    if (this.selectedItem) {
      if (this.selectedItem.id && this.selectedItem.type === "FILE") {
        disabled = false;
      }
    }
    return disabled;
  }

  onChooseDamsItem() {
    if (this.selectedItem) {
      if (this.ratio) {
        if (
          this.selectedItem.file_dimension &&
          "width" in this.selectedItem.file_dimension
        ) {
          if (
            calculateRatio(
              this.selectedItem.file_dimension.width,
              this.selectedItem.file_dimension.height
            ) !== this.ratio
          ) {
            this.$message({
              message: `${this.$t("banner.invalidRatio") as string} ${
                this.ratio
              }`,
              type: "error",
            });
            return;
          }
        }
      }

      if (this.allowFileType.length) {
        if (!this.allowFileType.includes(this.selectedItem.file_type)) {
          let message = "";
          if (this.allowFileType.includes("VIDEO")) {
            message = "general.onlyVideo";
          } else if (this.allowFileType.includes("IMAGE")) {
            message = "general.onlyImage";
          }
          this.$message({
            message: `${this.$t(message) as string}`,
            type: "error",
          });
          return;
        }
      }

      if (this.selectedItem.url) {
        this.$emit("setImageUrl", this.selectedItem.url);
      }

      this.getDamsUploadRef("reset");
      this.showUploadDams = false;
      this.selectedItem = new DamsItem();
    }
  }

  getDamsUploadRef(type: "reset" | "init") {
    const damsUploadRef: any = this.$refs.damsUploadRef;
    if (damsUploadRef) {
      if (type === "reset") {
        damsUploadRef.reset();
      } else if (type === "init") {
        damsUploadRef.init();
      }
    }
  }

  uploaded(url: string) {
    this.$emit("setImageUrl", url);
    this.showUploadPc = false;
  }
}
</script>
