<template>
  <div v-if="room" class="room-info">
    <div class="chat-header">
      <v-container fluid class="d-flex justify-space-between align-center">
        <v-btn
          id="btn-back"
          text
          :class="(($navigation && $navigation.canPop()) || $matrix.currentRoomId) ? 'v-visible' : 'v-hidden'"
          @click.stop="goBack()"
        >
          <v-icon>arrow_back</v-icon>
          <span class="d-none d-sm-block">{{ $t("menu.back") }}</span>
        </v-btn>
        <div class="room-name no-upper">{{ $t("room_info.title") }}</div>
        <v-btn
          v-if="!userCanPurgeRoom"
          id="btn-leave-room"
          color="black"
          depressed
          class="filled-button"
          @click.stop="showLeaveConfirmation = true"
          >👋 {{ $t("room_info.leave_room") }}</v-btn
        >
        <!-- PURGE ROOM -->
        <v-btn
          v-else
          id="btn-purge-room"
          color="red"
          class="filled-button"
          @click.stop="showPurgeConfirmation = true"
          >
          <v-icon light>$vuetify.icons.ic_moderator-delete</v-icon> {{ $t("room_info.purge") }}
        </v-btn>
      </v-container>
    </div>

    <div class="members ma-3 pa-3 mt-0 pt-0 text-center">
      <room-avatar-picker />
      <div :class="{'name':true,'cursor-default':!userCanPurgeRoom}">
        <span
          v-if="!isRoomNameEditMode"
          @click="onRoomNameClicked()"
        >
          {{ roomName }}
        </span>
        <v-text-field
          v-else
          v-model="editedRoomName"
          ref="editedRoomName"
          :rules="[(v) => !!v || $t('room.room_name_required')]"
          :error="roomNameErrorMessage != null"
          :error-messages="roomNameErrorMessage"
          required
          color="black"
          counter="50"
          background-color="white"
          autofocus
          maxlength="50"
          @blur="updateRoomName()"
          @keyup.enter="updateRoomName()"
          solo
        ></v-text-field>
      </div>
      <div :class="{'topic':true,'cursor-default':!userCanPurgeRoom}">
        <span
          v-if="!isRoomTopicEditMode"
          @click="onRoomTopicClicked()"
        >
          {{ roomTopic }}
        </span>
        <v-text-field
          v-else
          v-model="editedRoomTopic"
          ref="editedRoomTopic"
          :rules="[(v) => !!v || $t('room.room_topic_required')]"
          :error="roomTopicErrorMessage != null"
          :error-messages="roomTopicErrorMessage"
          required
          color="black"
          background-color="white"
          autofocus
          @blur="updateRoomTopic()"
          @keyup.enter="updateRoomTopic()"
          solo
        >
        </v-text-field>
      </div>
      <div :class="{'created-by':true, 'cursor-default':!userCanPurgeRoom}">
        {{ $t("room_info.created_by", { user: creator }) }}
      </div>
    </div>
    <copy-link :locationLink="publicRoomLink" i18nCopyLinkKey="copy_invite_link" />

    <v-card class="account ma-3" flat>
      <v-card-title class="h2">{{ $t("room_info.permissions") }}</v-card-title>
      <v-card-text>
        <v-select
          color="grey"
          v-if="roomJoinRule"
          :disabled="!userCanChangeJoinRule || updatingJoinRule"
          :items="joinRules"
          class="mt-4"
          v-model="roomJoinRule"
          item-value="id"
        >
          <template v-slot:selection="{ item }">
            <v-icon color="black" class="me-2">{{ item.icon }}</v-icon>
            {{ item.text }}
          </template>
          <template v-slot:item="{ item, attrs, on }">
            <v-list-item v-on="on" v-bind="attrs" #default="{ active }">
              <v-list-item-avatar>
                <v-icon color="black">{{ item.icon }}</v-icon>
              </v-list-item-avatar>
              <v-list-item-content>
                <v-list-item-title v-text="item.text"></v-list-item-title>
              </v-list-item-content>
              <v-list-item-action>
                <v-btn icon v-if="active">
                  <v-icon color="grey lighten-1">check</v-icon>
                </v-btn>
              </v-list-item-action>
            </v-list-item>
          </template>
        </v-select>

        <!-- <div v-if="anyoneCanJoin">
          <div>Anyone with a link can join.</div>
          <v-text-field
            :value="publicRoomLink"
            readonly
            append-icon="content_copy"
            filled
            type="text"
            @click:append="copyRoomLink"
          ></v-text-field>
        </div> -->
      </v-card-text>
    </v-card>

    <v-card class="account ma-3" flat v-if="(iAmAdmin() && availableRoomTypes.length > 1) || canChangeReadOnly()">
      <v-card-title class="h2 with-right-label"><div>{{ $t("room_info.experimental_features") }}</div><div></div></v-card-title>
      <v-card-text v-if="iAmAdmin() && availableRoomTypes.length > 1">
        <div class="d-flex flex-wrap">
          <div class="col-12 col-md-6 mr-auto pa-0">
            <div class="option-title">{{ $t('room_info.room_type') }}</div>
          </div>
          <div class="col-12 col-md-6 pa-0">
            <RoomTypeSelector v-model="roomType" />
          </div>
        </div>
      </v-card-text>
      <v-card-text class="with-right-label" v-if="canChangeReadOnly()">
        <div>
          <div class="option-title">{{ $t('room_info.read_only_room') }}</div>
          <div class="option-text">{{ $t('room_info.read_only_room_info') }}</div>
        </div>
        <v-switch
        v-model="readOnlyRoom"
      ></v-switch>
      </v-card-text>
    </v-card>

    <v-card class="members ma-3" flat>
      <v-card-title class="h2"
        >{{ $t("room_info.members") }}<v-spacer></v-spacer>
        <div>{{ members.length }}</div></v-card-title
      >
      <v-card-text>
        <div
          class="member ma-2"
          v-for="(member, index) in members"
          :key="member.userId"
          v-show="showAllMembers || index < SHOW_MEMBER_LIMIT"
          @click="toggleMemberExpanded(member)"
        >
          <v-avatar class="avatar" size="32" color="grey">
            <img v-if="memberAvatar(member)" :src="memberAvatar(member)" />
            <span v-else class="white--text headline">{{
              member.name.substring(0, 1).toUpperCase()
            }}</span>
          </v-avatar>
          <span class="user-name">
          {{
            member.userId == $matrix.currentUserId
              ? $t("room_info.user_you", {
                  user: member.user ? member.user.displayName : member.name,
                })
              : $t("room_info.user", {
                  user: member.user ? member.user.displayName : member.name,
                })
          }}
          </span>
          <span v-if="isAdmin(member)" class="user-power">
            {{ $t("room_info.user_admin") }}
          </span>
          <span v-else-if="isModerator(member)" class="user-power">
            {{ $t("room_info.user_moderator") }}
          </span>
          <div v-if="member.userId != $matrix.currentUserId && !$matrix.isDirectRoomWith(room, member.userId) && expandedMembers.includes(member)" class="start-private-chat clickable" @click="startPrivateChat(member.userId)">{{ $t("menu.start_private_chat") }}</div>
          <div v-if="canKickUser(member) || canBanUser(member)">
            <div v-if="member.userId != $matrix.currentUserId && expandedMembers.includes(member)" class="mt-2">{{ String.fromCharCode(160) }}</div>
            <div v-if="member.userId != $matrix.currentUserId && expandedMembers.includes(member) && canKickUser(member)" class="start-private-chat clickable" @click="kickUser(member)">{{ $t("menu.user_kick") }}</div>
            <div v-if="member.userId != $matrix.currentUserId && expandedMembers.includes(member) && canBanUser(member)" class="start-private-chat clickable" @click="banUser(member)">{{ $t("menu.user_kick_and_ban") }}</div>
          </div>
          <div v-if="member.userId != $matrix.currentUserId && expandedMembers.includes(member)" class="mt-2">{{ String.fromCharCode(160) }}</div>
          <div v-if="member.userId != $matrix.currentUserId && expandedMembers.includes(member) && !isAdmin(member) && canMakeAdmin(member)" class="start-private-chat clickable" @click="makeAdmin(member)">{{ $t("menu.user_make_admin") }}</div>
          <div v-if="member.userId != $matrix.currentUserId && expandedMembers.includes(member) && !isModerator(member) && !isAdmin(member) && canMakeModerator(member)" class="start-private-chat clickable" @click="makeModerator(member)">{{ $t("menu.user_make_moderator") }}</div>
          <div v-if="member.userId != $matrix.currentUserId && expandedMembers.includes(member) && isModerator(member) && canRevokeModerator(member)" class="start-private-chat clickable" @click="revokeModerator(member)">{{ $t("menu.user_revoke_moderator") }}</div>
          <DeviceList
            v-if="expandedMembers.includes(member)"
            :member="member"
          />
        </div>
        <div class="show-all" @click="showAllMembers = !showAllMembers" v-if="members.length > SHOW_MEMBER_LIMIT">
          {{
            showAllMembers ? $t("room_info.hide_all") : $t("room_info.show_all")
          }}
        </div>
      </v-card-text>
    </v-card>

    <!-- EXPORT CHAT -->
    <div style="text-align: center">
      <v-btn
        v-if="userCanExportChat"
        color="black"
        depressed
        class="filled-button"
        @click.stop="exportRoom"
        >{{ $t("room_info.export_room") }}</v-btn>
    </div>

    <div class="build-version">
      {{ $t("room_info.version_info", { version: buildVersion }) }}
    </div>

    <LeaveRoomDialog
      :show="showLeaveConfirmation"
      :room="room"
      @close="showLeaveConfirmation = false"
    />

    <PurgeRoomDialog
      :show="showPurgeConfirmation"
      :room="room"
      @close="showPurgeConfirmation = false"
    />

    <RoomExport :room="room" v-if="exporting" v-on:close="exporting = false" />
  </div>
</template>

<script>
import LeaveRoomDialog from "../components/LeaveRoomDialog";
import PurgeRoomDialog from "../components/PurgeRoomDialog";
import DeviceList from "../components/DeviceList";
import RoomExport from "../components/RoomExport";
import RoomAvatarPicker from "../components/RoomAvatarPicker";
import CopyLink from "../components/CopyLink.vue"
import RoomTypeSelector from "./RoomTypeSelector.vue";
import roomInfoMixin from "./roomInfoMixin";
import roomTypeMixin from "./roomTypeMixin";
import util, { STATE_EVENT_ROOM_TYPE } from "../plugins/utils";

export default {
  name: "RoomInfo",
  mixins: [roomInfoMixin, roomTypeMixin],
  components: {
    LeaveRoomDialog,
    PurgeRoomDialog,
    DeviceList,
    RoomExport,
    RoomAvatarPicker,
    RoomTypeSelector,
    CopyLink
  },
  data() {
    return {
      members: [],
      user: null,
      showAllMembers: false,
      showLeaveConfirmation: false,
      showPurgeConfirmation: false,
      expandedMembers: [],
      buildVersion: "",
      updatingJoinRule: false, // Flag if we are processing update curerntly
      joinRules: [
        {
          id: "public",
          text: this.$t("room_info.join_public"),
          icon: "link",
        },
        {
          id: "invite",
          text: this.$t("room_info.join_invite"),
          icon: "person_add",
        },
      ],
      SHOW_MEMBER_LIMIT: 5,
      exporting: false,
   };
  },
  mounted() {
    this.$matrix.on("Room.timeline", this.onEvent);
    this.updateMembers();
    this.user = this.$matrix.matrixClient.getUser(this.$matrix.currentUserId);

    // Display build version
    const version = require("!!raw-loader!../assets/version.txt").default;
    console.log("Version", version);
    this.buildVersion = version;
  },

  destroyed() {
    this.$matrix.off("Room.timeline", this.onEvent);
  },

  computed: {
    creator() {
      if (this.room) {
        const createEvent = this.room.currentState.getStateEvents(
          "m.room.create",
          ""
        );
        if (!createEvent) {
          console.warn(
            "Room " + this.roomId + " does not have an m.room.create event"
          );
          return "";
        }
        const creatorId = createEvent.getContent().creator;
        const member = this.room.getMember(creatorId);
        if (!member) {
          return creatorId;
        }
        return member.user ? member.user.displayName : member.name;
      }
      return "";
    },

    roomType: {
      get: function () {
        // if (this.room && this.room.tags) {
        //   let options = this.room.tags["ui_options"] || {}
        //   if (options["voice_mode"]) {
        //     return ROOM_TYPE_VOICE_MODE;
        //   } else if (options["file_mode"]) {
        //     return ROOM_TYPE_FILE_MODE;
        //   }
        // }
        // return ROOM_TYPE_DEFAULT;
        return util.roomDisplayTypeOverride(this.room) || this.roomDisplayType;
      },
      set: function (roomType) {
        if (this.room) {
          // let tags = this.room.tags || {};
          // let options = tags["ui_options"] || {}
          // options["voice_mode"] = (roomType == ROOM_TYPE_VOICE_MODE ? 1 : 0);
          // options["file_mode"] = (roomType == ROOM_TYPE_FILE_MODE ? 1 : 0);
          // tags["ui_options"] = options;
          // this.room.tags = tags;
          // this.$matrix.matrixClient.setRoomTag(this.room.roomId, "ui_options", options);
          if (this.iAmAdmin()) {
            this.$matrix.matrixClient.sendStateEvent(this.room.roomId, STATE_EVENT_ROOM_TYPE, { type: roomType });
          }
        }
      },
    },
    readOnlyRoom: {
      get: function () {
        return this.$matrix.isReadOnlyRoom(this.room.roomId);
      },
      set: function (readOnly) {
        this.$matrix.setReadOnlyRoom(this.room.roomId, readOnly);
      },
    }
  },

  watch: {
    room: {
      handler() {
        console.log("RoomInfo: Current room changed");
        this.updateMembers();
      },
    },
  },

  methods: {
    onEvent(event) {
      if (this.room && this.room.roomId == event.getRoomId()) {
        // For this room
        if (event.getType() == "m.room.member") {
        this.updateMembers();
      }
      }
    },

    updateMembers() {
      if (this.room) {
        const myUserId = this.$matrix.currentUserId;
        this.members = this.room.getJoinedMembers().sort((a, b) => {
          // Place ourselves at the top!
          if (a.userId == myUserId) {
            return -1;
          } else if (b.userId == myUserId) {
            return 1;
          }

          // Then sort by power level
          if (a.powerLevel > b.powerLevel) {
            return -1;
          } else if (b.powerLevel > a.powerLevel) {
            return 1;
          }

          // Then by name
          const aName = a.user ? a.user.displayName : a.name;
          const bName = b.user ? b.user.displayName : b.name;
          return aName.localeCompare(bName);
        });
      } else {
        this.members = [];
      }
    },

    memberAvatar(member) {
      if (member) {
        return member.getAvatarUrl(
          this.$matrix.matrixClient.getHomeserverUrl(),
          40,
          40,
          "scale",
          true
        );
      }
      return null;
    },

    viewProfile() {
      this.$navigation.push({ name: "Profile" }, 1);
    },

    toggleMemberExpanded(member) {
      const index = this.expandedMembers.indexOf(member);
      if (index > -1) {
        this.expandedMembers.splice(index, 1);
      } else {
        this.expandedMembers.push(member);
      }
    },

    /**
     * Set room join rule.
     * @param joinRule One of "invite" or "public". Currently always disables guest access.
     */
    setRoomJoinRule(joinRule) {
      const cli = this.$matrix.matrixClient;
      if (!this.room || !cli) {
        return;
      }

      if (joinRule == this.getRoomJoinRule()) {
        return; // No change
      }

      this.updatingJoinRule = true;
      var aliasPromise = Promise.resolve();
      // if (!this.room.getCanonicalAlias()) {
      //   const alias = "#" + this.room.roomId.substring(1);
      //   aliasPromise = cli.createAlias(alias, this.room.roomId);
      // }
      aliasPromise
        .then(() => {
          cli.sendStateEvent(
            this.room.roomId,
            "m.room.join_rules",
            { join_rule: joinRule },
            ""
          );
        })
        .then(() => {
          cli.sendStateEvent(
            this.room.roomId,
            "m.room.guest_access",
            { guest_access: "forbidden" },
            ""
          );
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          this.updatingJoinRule = 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);
        });
    },
    exportRoom() {
      if (this.room) {
        this.exporting = true;
      }
    },
    canKickUser(member) {
      if (this.room) {
        const myUserId = this.$matrix.currentUserId;
        const me = this.room.getMember(myUserId);
        return me && me.powerLevel > member.powerLevel && this.room.currentState && this.room.currentState.hasSufficientPowerLevelFor("kick", me.powerLevel);
      }
      return 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 change power levels in the room, i.e. make read only room
     */
    canChangeReadOnly() {
      if (!this.$config.experimental_read_only_room) { return false; }
      if (this.room) {
        return this.room.currentState && this.room.currentState.maySendStateEvent("m.room.power_levels", this.$matrix.currentUserId);
      }
      return false;
    },
    iAmAdmin() {
      if (this.room) {
        return this.room.currentState && this.room.currentState.maySendStateEvent("m.room.power_levels", this.$matrix.currentUserId);
      }
      return false;
    },
    // TODO - following power level comparisons assume that default power levels are used in the room!
    isAdmin(member) {
      return member.powerLevelNorm > 50;
    },
    isModerator(member) {
      return member.powerLevelNorm > 0 && member.powerLevelNorm <= 50;
    },
    /**
     * 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)
      }
    },
    makeModerator(member) {
      if (this.room) {
        this.$matrix.makeModerator(this.room.roomId, member.userId)
      }
    },
    revokeModerator(member) {
      if (this.room) {
        this.$matrix.revokeModerator(this.room.roomId, member.userId)
      }
    },
    kickUser(member) {
      if (this.room) {
        this.$matrix.kickUser(this.room.roomId, member.userId)
      }
    },
    banUser(member) {
      if (this.room) {
        this.$matrix.banUser(this.room.roomId, member.userId)
      }
    },

    /**
     * Go back to previous page, or if none on the stack, go back to current room view.
     */
    goBack() {
      if (this.$navigation.canPop()) {
        this.$navigation.pop();
      } else if (this.$matrix.currentRoomId) {
        this.$navigation.push(
        {
          name: "Chat",
          params: { roomId: util.sanitizeRoomId(this.$matrix.currentRoomId) },
        },
        -1
      );
      }
    },
  },
};
</script>

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

</style>