<template>
  <MessageOutgoing v-bind="{ ...$props, ...$attrs }">
    <div class="bubble">
      <div class="original-message" v-if="inReplyToText">
        <div class="original-message-sender">{{ inReplyToSender }}</div>
        <div class="original-message-text" v-html="linkify($$sanitize(inReplyToText))" />
      </div>

      <div class="message">
        <div class="message-upload-progress" v-if="unref(uploadBatch?.sendingStatus) === 'sending'">
          <v-progress-circular
            class="message-upload-progress__progress clickable"
            :model-value="unref(uploadBatch?.progressPercent ?? 0)"
            color="white"
            bg-color="rgba(255,255,255,0.5)"
            width="2"
            size="16"
            @click.stop="cancelUpload"
          >
            <v-icon size="8">close</v-icon> </v-progress-circular
          >{{ uploadBatch?.progressPercent }}%
        </div>
        <div class="message-upload-progress clickable" @click.stop="retryUpload" v-else-if="unref(uploadBatch?.sendingStatus) === 'failed'">
            <v-icon size="12">$vuetify.icons.ic_arrow_narrow</v-icon>
          <div>{{ t("global.retry") }}</div>
        </div>
        <SwipeableThumbnailsView :items="items" v-if="room.displayType == ROOM_TYPE_CHANNEL" v-bind="$attrs" />
        <v-container v-else fluid class="imageCollection">
          <v-row wrap>
            <v-col v-for="{ size, item } in layoutedItems" :key="item.file.name + item.file.size" :cols="size">
              <ThumbnailView :previewOnly="true" :item="item" />
            </v-col>
          </v-row>
        </v-container>
        <span v-html="linkify($$sanitize(messageText))" v-if="messageText" />
        <span class="edit-marker" v-if="event && event.replacingEventId() && !event.isRedacted()">
          {{ t("message.edited") }}
        </span>
      </div>
    </div>
  </MessageOutgoing>
</template>

<script setup lang="ts">
import MessageOutgoing from "./MessageOutgoing.vue";
import { MessageProps, useMessage } from "./useMessage";
import { ROOM_TYPE_CHANNEL } from "@/plugins/utils";
import ThumbnailView from "../../file_mode/ThumbnailView.vue";
import SwipeableThumbnailsView from "../channel/SwipeableThumbnailsView.vue";
import { inject, ref, Ref, unref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Attachment, AttachmentBatch } from "../../../models/attachment";

const { t } = useI18n();
const $matrix: any = inject("globalMatrix");
const $$sanitize: any = inject("globalSanitize");

let items: Ref<Attachment[]> = ref([]);
const layoutedItems: Ref<{ size: number; item: Attachment }[]> = ref([]);

const uploadBatch: Ref<AttachmentBatch | undefined> = ref(undefined);

const props = defineProps<MessageProps>();

const { room } = props;

const {
  event,
  inReplyToSender,
  inReplyToText,
  messageText,
  linkify,
} = useMessage($matrix, t, props, undefined, undefined);

const cancelUpload = () => {
  if (uploadBatch.value) {
    uploadBatch.value.cancel();
  }
}

const retryUpload = () => {
  if (uploadBatch.value) {
    uploadBatch.value.send(uploadBatch.value.sendingRootMessage?.value ?? "");
  }
}

const layout = () => {
  if (!items.value || items.value.length == 0) {
    layoutedItems.value = [];
    return;
  }
  let array = items.value.slice(0);
  let rows = [];
  while (array.length > 0) {
    if (array.length >= 7) {
      rows.push({ size: 6, item: array[0] });
      rows.push({ size: 6, item: array[1] });
      rows.push({ size: 12, item: array[2] });
      rows.push({ size: 3, item: array[3] });
      rows.push({ size: 3, item: array[4] });
      rows.push({ size: 3, item: array[5] });
      rows.push({ size: 3, item: array[6] });
      array = array.slice(7);
    } else if (array.length >= 3) {
      rows.push({ size: 6, item: array[0] });
      rows.push({ size: 6, item: array[1] });
      rows.push({ size: 12, item: array[2] });
      array = array.slice(3);
    } else if (array.length >= 2) {
      rows.push({ size: 6, item: array[0] });
      rows.push({ size: 6, item: array[1] });
      array = array.slice(2);
    } else {
      rows.push({ size: 12, item: array[0] });
      array = array.slice(1);
    }
  }
  layoutedItems.value = rows;
};

watch(
  event,
  (updated) => {
    const batch = updated?.uploadBatch;
    if (batch) {
      uploadBatch.value = updated?.uploadBatch;
      items = ref(batch.attachments);
      layout();
    }
  },
  { immediate: true }
);
</script>

<style lang="scss">
@use "@/assets/css/chat.scss" as *;
</style>

<style lang="scss" scoped>
.bubble {
  width: 100%;
}

.imageCollection {
  border-radius: 15px;
  padding: 0;
  overflow: hidden;

  .row {
    margin: -4px; // Compensate for column padding, so the border-radius above looks round!
    padding: 0;
  }

  .col {
    padding: 2px;
  }

  .file-item {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.6rem;
    flex-direction: column;
    padding: 20px;
  }
}

.message-upload-progress {
  z-index: 1;
  position: absolute;
  top: 4px;
  left: 4px;
  height: 20px;
  border-radius: 10px;
  background-color: black;
  color: white;
  font-family: "Inter";
  font-weight: 400;
  font-style: normal;
  font-size: 10px;
  line-height: 125%;
  letter-spacing: 0.4px;
  display: flex;
  align-items: center;
  padding-left: 2px;
  padding-right: 4px;
  .message-upload-progress__progress {
    margin-right: 3px;
  }
}
</style>
