<template>
  <v-dialog
    v-model="showDialog"
    v-show="room"
    class="ma-0 pa-0"
    :width="$vuetify.breakpoint.smAndUp ? '688px' : '95%'"
  >
    <div class="dialog-content text-center member-action-dialog">
      <div>
        <v-avatar class="avatar" size="56" color="grey">
          <img v-if="memberAvatar(activeMember)" :src="memberAvatar(activeMember)" />
          <span v-else class="white--text headline">{{
            activeMember.name.substring(0, 1).toUpperCase()
          }}</span>
        </v-avatar>
        <div>
          <span class="user-name">
          {{
            activeMember.userId == $matrix.currentUserId
              ? $t("room_info.user_you", {
                  user: activeMemberName(activeMember)
                })
              : $t("room_info.user", {
                  user: activeMemberName(activeMember)
                })
          }}
          </span>
          <span v-if="isAdmin(activeMember)" class="user-power">
            {{ $t("room_info.user_admin") }}
          </span>
          <span v-else-if="isModerator(activeMember)" 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: activeMemberName(activeMember)}) }}</span>
          <span v-else>{{ $t("room_info.shared_room_number_more", {count: sharedRooms.length, name: activeMemberName(activeMember)}) }}</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">
        <v-btn text 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 left>$vuetify.icons.direct_chat</v-icon>  {{ $t("menu.direct_chat") }}
        </v-btn>
        <div v-if="canBanUser(activeMember)">
          <v-btn text x-large block v-if="activeMember.userId != $matrix.currentUserId && canBanUser(activeMember)" class="start-private-chat clickable d-block text-none justify-start" @click="banUser(activeMember)">
            <v-icon left>$vuetify.icons.kickout</v-icon> {{ $t("menu.user_kick_and_ban") }}
          </v-btn>
        </div>
        <v-btn text x-large block v-if="activeMember.userId != $matrix.currentUserId && !isAdmin(activeMember) && canMakeAdmin(activeMember)" class="start-private-chat clickable d-block text-none justify-start" @click="makeAdmin(activeMember)">
          <v-icon left>$vuetify.icons.make_admin</v-icon> {{ $t("menu.user_make_admin") }}
        </v-btn>
        <v-btn text x-large block v-if="activeMember.userId != $matrix.currentUserId && !isModerator(activeMember) && !isAdmin(activeMember) && canMakeModerator(activeMember)" class="start-private-chat clickable d-block text-none justify-start" @click="makeModerator(activeMember)">
          <v-icon left>$vuetify.icons.make_moderator</v-icon> {{ $t("menu.user_make_moderator") }}
        </v-btn>
        <v-btn text x-large block v-if="activeMember.userId != $matrix.currentUserId && isModerator(activeMember) && canRevokeModerator(activeMember)" class="start-private-chat clickable d-block text-none justify-start" @click="revokeModerator(activeMember)">
          <v-icon left>$vuetify.icons.revoke</v-icon> {{ $t("menu.user_revoke_moderator") }}
        </v-btn>
      </div>
    </div>
  </v-dialog>
</template>
<script>
import roomInfoMixin from "./roomInfoMixin";
import DeviceList from "../components/DeviceList";
import util from "../plugins/utils";

export default {
  name: "MemberActionDialog",
  mixins: [roomInfoMixin],
  components: {
    DeviceList
  },
  props: {
    show: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
    activeMember: {
      type: Object
    }
  },
  data() {
    return {
      showDialog: false
    };
  },
  computed: {
    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;
      }, []);
    }
  },
  watch: {
    show: {
      handler(newVal, ignoredOldVal) {
        this.showDialog = newVal;
      }
    },
    showDialog() {
      if (!this.showDialog) {
        this.$emit("close");
      }
    },
  },

  methods: {
    activeMemberName(activeMember) {
      return activeMember.user ? activeMember.user.displayName : activeMember.name
    },
    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 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(member) {
      if (this.room) {
        this.$matrix.makeAdmin(this.room.roomId, member.userId)
        this.showDialog = false;
      }
    },
    makeModerator(member) {
      if (this.room) {
        this.$matrix.makeModerator(this.room.roomId, member.userId)
        this.showDialog = false;
      }
    },
    revokeModerator(member) {
      if (this.room) {
        this.$matrix.revokeModerator(this.room.roomId, member.userId)
        this.showDialog = false;
      }
    },
    banUser(member) {
      if (this.room) {
        this.$matrix.banUser(this.room.roomId, member.userId)
        this.showDialog = false;
      }
    },
  },
};
</script>

<style lang="scss">
@import "@/assets/css/chat.scss";
</style>