// import HttpService from "~/services/httpService";
import chatApi from "@chat/apis/chatApi";
// import repoApi from "~/apis/repoApi";

export default {
  beforeMount() {
    this.httpService = useNuxtApp()["$http"];
  },
  methods: {
    closeList() {
      this.SET_SIDEBAR_LIST_STATUS();
      // this.footerAction = actionName;
      this.menubarStatus = !this.menubarStatus;

      // this.$root.$emit("show-search", this.menubarStatus);
    },
    initServices() {
      // const headers = {
      //   "app-id": import.meta.env.VITE_APP_ID,
      //   lang: import.meta.env.VITE_LANG,
      //   "app-version-code": import.meta.env.VITE_APP_VERSION,
      // };

      // this.fileUploadHttpService = new HttpService(
      //   import.meta.env.VITE_MESSAGE_BASE_URL,
      //   {
      //     "Content-Type": "multipart/form-data",
      //   }
      // );

      // this.issueHttpService = new HttpService(
      //   import.meta.env.VITE_REPO_BASE_URL + "jahat/"
      // );

      // this.httpService = new HttpService(
      //   import.meta.env.VITE_BASE_URL
      //   // headers
      // );

      // this.keyValueHttpService = new HttpService(
      //   import.meta.env.VITE_KEY_VALUE_BASE_URL
      // );

      // this.messageHttpService = new HttpService(
      //   import.meta.env.VITE_MESSAGE_BASE_URL
      // );
    },
    openAuthModal() {
      if (!this.isGuest && this.listGetter?.show_joined) {
        this.$root.$emit(
          "authenticated-by-modal",
          this.$route.query["invite-id"]
        );
      }
      // fired event cached in the Group.vue and ChatList.vue
      else this.showAuthModal = true;
    },
    closeAuthModal() {
      this.showAuthModal = false;
    },
    getFileExtension(filename) {
      return filename?.split("/").pop();
    },
    formatBytes(bytes, decimals = 2) {
      if (!+bytes) return "0 Bytes";

      const k = 1024;
      const dm = decimals < 0 ? 0 : decimals;
      const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

      const i = Math.floor(Math.log(bytes) / Math.log(k));

      return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
    },
    async handlePasteEvent(e) {
      this.uploadDescription = null;

      // navigator is not supported in the firefox.
      if (!navigator.userAgent.includes("Firefox/")) {
        e.preventDefault();

        // catching the pasted text and place it into the comment form.
        navigator.clipboard
          .readText()
          .then((text) => {
            if (this.showReplays) {
              this.mySwalConfirm({
                icon: "info",
                title: "جایگزاری در فرم پیام ها؟",
                html: "",
                text: "متن کپی شده در فرم اصلی جایگزاری شود یا فرم پاسخ ها؟",
                confirmButtonText: "بله",
                cancelButtonText: "خیر",
                didOpen: (toast) => {},
                showCloseButton: true,
                willClose: () => {
                },
                didClose() {
                },
              }).then((result) => {
                if (result.isConfirmed) {
                  if (this.userMessage?.length) {
                    this.userMessage += " " + text;
                  } else {
                    this.userMessage = text;
                  }

                  // this.userMessage = this.userMessage
                  //   ? this.userMessage + text
                  //   : text;
                } else if (result.isDismissed && result.dismiss == "cancel") {
                  if (this.replayText?.length) {
                    this.replayText += " " + text;
                  } else {
                    this.replayText = text;
                  }
                }
                // this.replayText = this.replayText
                //   ? this.replayText + text
                //   : text;
              });

              // const res = confirm("جایگزاری در فرم پیام ها؟");
              // if (res) this.userMessage = text;
              // else this.replayText = text;
            } else {
              if (this.userMessage?.length) {
                this.userMessage += " " + text;
              } else {
                this.userMessage = text;
              }
            }
            // this.userMessage = this.userMessage
            //   ? this.userMessage + text
            //   : text;
          })
          .catch((err) => {
            console.error("Failed to read clipboard contents: ", err);
          });
      }

      const clipboardItems =
        typeof navigator?.clipboard?.read === "function"
          ? await navigator.clipboard.read()
          : e.clipboardData.files;

      for (const clipboardItem of clipboardItems) {
        let blob;

        if (clipboardItem.type?.startsWith("image/")) {
          let fileType = clipboardItem?.type?.split("/")[1];

          // For files from `e.clipboardData.files`.
          blob = clipboardItem;

          this.files = [];
          this.files.push(new File([blob], fileType));
          // this.files.push(blob);
          this.showDroppedList = true;
          this.dropBoxClass = "messages";
        } else {
          // For files from `navigator.clipboard.read()`.
          const imageTypes = clipboardItem.types?.filter((type) =>
            type.startsWith("image/")
          );
          for (const imageType of imageTypes) {
            let fileType = imageType.split("/")[1];

            blob = await clipboardItem.getType(imageType);

            this.files = [];
            this.files.push(new File([blob], fileType));
            this.showDroppedList = true;
            this.dropBoxClass = "messages";
          }
        }
      }
      // 0: "image/png"

      // 0: "text/plain"
      // 1: "text/html"
    },
    checkPermisionBeforGetList() {
      this.checkPermissions({
        permission: `${this.$route.name}_list`,
        _this: this,
      })
        .then(() => {
          this.toLastItem();
          this.canView = true;
        })
        .catch(() => {
          this.canView = false;
        });
    },
    replaceTextWithLink(text) {
      const clonedText = text;
      try {
        const Rexp =
          /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g;

        // Replace the RegExp content by HTML element
        return text.replace(
          Rexp,
          `<a href="${clonedText}" title="${clonedText}" target='_blank'>${clonedText}</a>`
        );
      } catch (err) {
        return text;
      }
    },
    saveLabel(selectedLabel, comment) {
      if (this.savingComment) return;
      this.savingComment = true;

      let payload = {
        group_id: this.listGetter.id,
        id: comment.id,
        entity_field_id: selectedLabel,
      };

      let url = "message/" + chatApi.messages.create;

      this.httpService
        .formDataRequest(url, payload)
        .then((res) => {
          comment.entity_field_id = selectedLabel;
          // this.getMessages();
        })

        .catch((err) => {})
        .finally(() => {
          this.savingComment = false;
        });
    },
    getMids(messages) {
      return messages.map((message) => message.id);
    },
    showfilters() {
      this.$emit("my-event", (this.statusPage = 1));
    },
    closefilter() {
      this.showFilter = false;
    },
    groupDescription(text) {
      let res = "";
      try {
        res = JSON.parse(text);
      } catch (err) {
        res = text;
      }
      return res;
    },
    showMessageSearch() {
      // this.SET_SIDEBAR_LIST_STATUS(false);
      this.$root.$emit("show-search", true);
      // this.$emit("show-search");
    },
    async onResult(data) {
      // در صورت استفاده از پلاگین ،برای متوقف کردن
      // علامت ضبط صدا از روی تب، بایستی از این کدها استفاده شود.
      // const audioTracks = this.mediaStream.getAudioTracks();
      // audioTracks.forEach((element) => {
      // element.stop();
      // });

      this.files = [];
      this.files.push(new File([data], "mp3"));

      // if (this.abortRecord) return;
      // this.abortRecord = true;

      this.mainSaveFiles().then(() => {
        // this.recording = false;
        // this.abortRecord = false;
      });
    },
    async makeLink(comment) {
      const params = new URLSearchParams({
        ["group-id"]: this.listGetter.id,
        ["message-id"]: comment.id,
      });
      let link = location.origin + location.pathname + "?" + params.toString();

      link += "#chat-item-" + comment.id;

      try {
        await navigator.clipboard.writeText(link);
        this.mySwalToast({
          html: "لینک کپی شد.",
        });
      } catch (err) {
        

        this.mySwalToast({
          html: "خطایی رخ داد.لطفا دوباره امتحان کنید.",
        });
      }
    },
    updateMessageCount() {
      const currentUserModel = {
        avatar: this.currentUser.user_data.avatar,
        color: 40080,
        first_name: this.currentUser.user_data.avatar,
        full_name: this.currentUser.user_data.avatar,
        id: this.currentUser.user_id,
        last_name: this.currentUser.user_data.last_name,
        user_id: this.currentUser.user_id,
        username: this.currentUser.user_data.username,
      };
      // finding the target comment by id.
      this.localComments.forEach((com) => {
        // if comment id is equal to the comment user want to replay.
        if (com.id == this.replayTo.id) {
          // increment the comment count.
          this.$set(com.replys, "count", ++com.replys.count);

          // if comment has users, then
          if (com.replys.users.length) {
            // finding the index of the user by current user id.
            const index = com.replys.users.find(
              (user) => user.user_id == this.currentUser.user_id
            );

            // if current user didn't exist, then push it to comments users array.
            if (index == -1) com.replys.users.push(currentUserModel);
          } else com.replys.users.push(currentUserModel);
        }
        // com.replys.count++;
      });

      // let payload = {
      //   group_id: this.listGetter.id,
      //   contact_id:
      //     this.$route.name == "privates" ? this.listGetter.user : undefined,
      //   ...this.pagination,
      // };

      // this.httpService
      //   .postRequest(chatApi.messages.virtualList, payload)
      //   .then((response) => {
      //     if (response.data && response.data.length) {
      //       // this.replayUsers = structuredClone(response.users);
      //       this.localComments = response.data;
      //       this.setUsers(this.localComments, response.users);
      //     }
      //   });
    },
    setUsers(list, responseUsers) {
      list.forEach((listItem) => {
        listItem.user = responseUsers.find(
          (user) => user.user_id == listItem.user
        );
        if (listItem.replys)
          listItem.replys.users = this.allReplayers(listItem, responseUsers);
      });
    },
    limitText(count) {
      return `و ${count} کاربر دیگر`;
    },
    parseText(text) {
      try {
        return JSON.parse(text);
      } catch (err) {
        return text;
      }
    },
    resetPagination() {
      this.pagination = {
        page: 0,
        total: 0,
        pageTop: 0,
        pageBottom: 1,
        seenDate: null,
      };
    },
  },
};