<template>
  <v-dialog
    v-model="showDialog"
    v-bind="{ ...$attrs }"
    class="ma-0 pa-0"
    :width="$vuetify.display.smAndUp ? '688px' : '95%'"
    scroll-strategy="none"
  >
    <div class="dialog-content text-center member-action-dialog">
      <div class="pt-4">
        <v-avatar class="avatar" size="56" color="grey">
          <AuthedImage v-if="memberAvatarComp" :src="memberAvatarComp" />
          <span v-else class="text-white headline">{{ firstLetterUserName }}</span>
        </v-avatar>
        <div>
          <span class="user-name">
          {{
            isCurrentUser
              ? $t("room_info.user_you", {
                  user: activeMemberNameComp
                })
              : $t("room_info.user", {
                  user: activeMemberNameComp
                })
          }}
          </span>
          <span v-if="isAdminComp" class="user-power">
            {{ $t("room_info.user_admin") }}
          </span>
          <span v-else-if="isModeratorComp" class="user-power">
            {{ $t("room_info.user_moderator") }}
          </span>
        </div>
        <template v-if="activeMember.userId != $matrix.currentUserId && sharedRooms.length">
          <span v-if="sharedRooms.length < 3">{{ $t("room_info.shared_room_number", {count: sharedRooms.length, name: activeMemberNameComp}) }}</span>
          <span v-else>{{ $t("room_info.shared_room_number_more", {count: sharedRooms.length, name: activeMemberNameComp}) }}</span>
          <p class="font-weight-light">{{ sharedRooms.slice(0, 3).join(", ") }}</p>
        </template>
      </div>
      <DeviceList :member="activeMember" />
      <div class="py-3" v-if="activeMember.userId != $matrix.currentUserId">
        <div v-if="activeMember.membership == 'knock'">
        </div>
        <div v-else>
        <v-btn variant="text" size="x-large" block v-if="activeMember.userId != $matrix.currentUserId && !$matrix.isDirectRoomWith(room, activeMember.userId)" class="start-private-chat clickable d-block text-none justify-start" @click="startPrivateChat(activeMember.userId)">
          <v-icon start>$vuetify.icons.direct_chat</v-icon>  {{ $t("menu.direct_chat") }}
        </v-btn>
        <div v-if="canBanUserComp">
          <v-btn variant="text" size="x-large" block v-if="activeMember.userId != $matrix.currentUserId && canBanUserComp" class="start-private-chat clickable d-block text-none justify-start" @click="banUser">
            <v-icon start>$vuetify.icons.kickout</v-icon> {{ $t("menu.user_kick_and_ban") }}
          </v-btn>
        </div>
        <v-btn variant="text" size="x-large" block v-if="activeMember.userId != $matrix.currentUserId && !isAdminComp && canMakeAdminComp" class="start-private-chat clickable d-block text-none justify-start" @click="makeAdmin">
          <v-icon start>$vuetify.icons.make_admin</v-icon> {{ $t("menu.user_make_admin") }}
        </v-btn>
        <v-btn variant="text" size="x-large" block v-if="activeMember.userId != $matrix.currentUserId && isAdminComp && canRevokeAdminComp" class="start-private-chat clickable d-block text-none justify-start" @click="revokeAdmin">
          <v-icon start>$vuetify.icons.make_admin</v-icon> {{ $t("menu.user_revoke_admin") }}
        </v-btn>
        <v-btn variant="text" size="x-large" block v-if="activeMember.userId != $matrix.currentUserId && !isModeratorComp && !isAdminComp && canMakeModeratorComp" class="start-private-chat clickable d-block text-none justify-start" @click="makeModerator">
          <v-icon start>$vuetify.icons.make_moderator</v-icon> {{ $t("menu.user_make_moderator") }}
        </v-btn>
        <v-btn variant="text" size="x-large" block v-if="activeMember.userId != $matrix.currentUserId && isModeratorComp && canRevokeModeratorComp" class="start-private-chat clickable d-block text-none justify-start" @click="revokeModerator">
          <v-icon start>$vuetify.icons.revoke</v-icon> {{ $t("menu.user_revoke_moderator") }}
        </v-btn>
        </div>
      </div>
    </div>
  </v-dialog>

  <ConfirmationDialog :message="$t('room_info.confirm_make_admin')" v-model="showConfirmMakeAdmin" v-on:ok="doMakeAdmin" />
  <ConfirmationDialog :message="$t('room_info.confirm_revoke_admin')" v-model="showConfirmRevokeAdmin" v-on:ok="doRevokeAdmin" />
  <ConfirmationDialog :message="$t('room_info.confirm_make_moderator')" v-model="showConfirmMakeModerator" v-on:ok="doMakeModerator" />
  <ConfirmationDialog :message="$t('room_info.confirm_revoke_moderator')" v-model="showConfirmRevokeModerator" v-on:ok="doRevokeModerator" />
  <ConfirmationDialog :message="$t('room_info.confirm_ban')" v-model="showConfirmBan" v-on:ok="doBanUser" />
</template>
<script>
import roomInfoMixin from "./roomInfoMixin";
import DeviceList from "../components/DeviceList";
import AuthedImage from "./AuthedImage.vue";
import util from "../plugins/utils";
import RoomDialogBase from "./RoomDialogBase.vue";
import ConfirmationDialog from "./ConfirmationDialog.vue";
import { consoleError } from "vuetify/lib/util/console.mjs";

export default {
  name: "UserProfileDialog",
  extends: RoomDialogBase,
  components: {
    DeviceList,
    AuthedImage,
    ConfirmationDialog
  },
  props: {
    activeMember: {
      type: Object,
      default: function () {
        return null;
      }
    }
  },
  data() {
    return {
      showConfirmMakeAdmin: false,
      showConfirmRevokeAdmin: false,
      showConfirmMakeModerator: false,
      showConfirmRevokeModerator: false,
      showConfirmBan: false
    };
  },
  computed: {
    canRevokeAdminComp () {
      return this.canRevokeAdmin(this.activeMember)
    },
    canRevokeModeratorComp () {
      return this.canRevokeModerator(this.activeMember)
    },
    isModeratorComp() {
      return this.isModerator(this.activeMember)
    },
    canMakeModeratorComp() {
      return this.canMakeModerator(this.activeMember)
    },
    canMakeAdminComp() {
      return this.canMakeAdmin(this.activeMember)
    },
    canBanUserComp() {
      return this.canBanUser(this.activeMember)
    },
    isAdminComp() {
      return this.isAdmin(this.activeMember)
    },
    activeMemberNameComp() {
      return this.activeMember.user ? this.activeMember.user.displayName : this.activeMember.name
    },
    isCurrentUser() {
      return this.activeMember.userId == this.$matrix.currentUserId
    },
    firstLetterUserName() {
      return this.activeMember.name.substring(0, 1).toUpperCase()
    },
    memberAvatarComp() {
      return this.memberAvatar(this.activeMember)
    },
    joinedMembersByRoomId() {
      const joinedRooms = this.$matrix.joinedRooms.filter(room => !this.$matrix.isDirectRoom(room)) || [];
      return joinedRooms.map(room => ({
        roomId: room.roomId,
        roomName: room.name,
        memberIds: room.getJoinedMembers().map(({ userId }) => userId)
      }));
    },
    sharedRooms() {
      return this.joinedMembersByRoomId.reduce((sharedRooms, room) => {
        if (room.roomId !== this.room.roomId && room.memberIds.includes(this.activeMember.userId)) {
          sharedRooms.push(room.roomName);
        }
        return sharedRooms;
      }, []);
    }
  },
  methods: {
    shouldShow() {
      return this.modelValue && this.room && this.activeMember ? true : false;
    },
    startPrivateChat(userId) {
      this.$matrix
        .getOrCreatePrivateChat(userId)
        .then((room) => {
          this.$nextTick(() => {
            this.$navigation.push(
              {
                name: "Chat",
                params: {
                  roomId: util.sanitizeRoomId(
                    room.getCanonicalAlias() || room.roomId
                  ),
                },
              },
              -1
            );
          });
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          this.showDialog = false;
        });
    },
    canBanUser(member) {
      if (this.room) {
        const myUserId = this.$matrix.currentUserId;
        const me = this.room.getMember(myUserId);
        return me && me.powerLevelNorm > member.powerLevelNorm && this.room.currentState && this.room.currentState.hasSufficientPowerLevelFor("ban", me.powerLevel);
      }
      return false;
    },
    /**
     * Return true if WE can make the member an admin
     * @param  member
     */
    canMakeAdmin(ignoredmember) {
      if (this.room) {
        const myUserId = this.$matrix.currentUserId;
        const me = this.room.getMember(myUserId);
        return me && this.isAdmin(me);
      }
      return false;
    },
    /**
     * Return true if WE can "unmake" the member an administraor (= we are creator of the room)
     * @param  member
     */
     canRevokeAdmin(member) {
      if (this.room) {
        // TODO - not supposed to parse room versions as int.
        const roomVersion = parseInt(this.room.getVersion()?.split(".").reverse()[0] ?? "0");
        const myUserId = this.$matrix.currentUserId;
        return roomVersion > 11 && this.room.getCreator() === myUserId;
      }
      return false;
    },

    /**
     * Return true if WE can make the member a moderator
     * @param  member
     */
     canMakeModerator(ignoredmember) {
      if (this.room) {
        const myUserId = this.$matrix.currentUserId;
        const me = this.room.getMember(myUserId);
        return me && this.isAdmin(me);
      }
      return false;
    },
    /**
     * Return true if WE can "unmake" the member a moderator
     * @param  member
     */
     canRevokeModerator(member) {
      if (this.room) {
        const myUserId = this.$matrix.currentUserId;
        const me = this.room.getMember(myUserId);
        return me && this.isAdmin(me) && me.powerLevel > member.powerLevel;
      }
      return false;
    },
    makeAdmin() {
      if (this.room && this.activeMember) {
        this.showConfirmMakeAdmin = true;
        this.showDialog = false;
      }
    },
    doMakeAdmin() {
      if (this.room && this.activeMember) {
        this.$matrix.makeAdmin(this.room.roomId, this.activeMember.userId)
        this.showDialog = false;
      }
    },
    revokeAdmin() {
      if (this.room && this.activeMember) {
        this.showConfirmRevokeAdmin = true;
        this.showDialog = false;
      }
    },
    doRevokeAdmin() {
      if (this.room && this.activeMember) {
        this.$matrix.revokeAdmin(this.room.roomId, this.activeMember.userId)
        this.showDialog = false;
      }
    },

    makeModerator() {
      if (this.room && this.activeMember) {
        this.showConfirmMakeModerator = true;
        this.showDialog = false;
      }
    },
    doMakeModerator() {
      if (this.room && this.activeMember) {
        this.$matrix.makeModerator(this.room.roomId, this.activeMember.userId)
        this.showDialog = false;
      }
    },
    revokeModerator() {
      if (this.room && this.activeMember) {
        this.showConfirmRevokeModerator = true;
        this.showDialog = false;
      }
    },
    doRevokeModerator() {
      if (this.room && this.activeMember) {
        this.$matrix.revokeModerator(this.room.roomId, this.activeMember.userId)
        this.showDialog = false;
      }
    },
    banUser() {
      if (this.room && this.activeMember) {
        this.showConfirmBan = true;
        this.showDialog = false;
      }
    },
    doBanUser() {
      if (this.room && this.activeMember) {
        this.$matrix.banUser(this.room.roomId, this.activeMember.userId)
      }
    }
  },
};
</script>

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