<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-card-title class="h2">{{ $t("room_info.message_retention") }}</v-card-title>
      <v-card-text v-if="canViewRetentionPolicy">
        <v-list v-if="canChangeRetentionPolicy">
          <v-list-item link v-on:click="showMessageRetentionDialog = true" class="px-0">
            <v-list-item-avatar class="mr-0 pb-0 mb-0">
              <v-img
                contain
                width="24"
                height="24"
                src="@/assets/icons/timer.svg"
              />
            </v-list-item-avatar>
            <v-list-item-content class="pb-0">
              {{ messageRetentionDisplay }}
            </v-list-item-content>

            <v-list-item-action class="pb-0 mb-0">
              <v-icon>arrow_drop_down</v-icon>
            </v-list-item-action>
          </v-list-item>
          <hr />
        </v-list>
        <div>
          {{ $t("room_info.message_retention_info") }}
        </div>
      </v-card-text>

    </v-card>

    <v-card class="account ma-3" flat v-if="canChangeReadOnly()">
      <v-card-title class="h2">{{ $t("room_info.moderation") }}</v-card-title>
      <v-card-text class="" v-if="canChangeReadOnly()">
        <div class="with-right-label" style="align-items:center;height:36px">  
        <div class="option-title"><v-icon>$vuetify.icons.ic_eye</v-icon> {{ $t('room_info.read_only_room') }}</div>
          <v-switch class="ma-0" v-model="readOnlyRoom"></v-switch>
        </div>
        <div class="option-text">{{ $t('room_info.read_only_room_info') }}</div>
    </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-list>
        <v-list-item-group>
          <template  v-for="(member, index) in members" >
            <v-list-item
              :key="member.userId"
              class="member"
              v-show="showAllMembers || index < SHOW_MEMBER_LIMIT"
              @click="onListItemClick(member)"
            >
              <div>
                <div class="user-icon-with-badge">
                  <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>
                  <v-avatar circle class="user-badge" size="15" v-if="isAdmin(member) || isModerator(member)">
                    <v-icon style="min-width: 15px;min-height: 15px;">{{ `$vuetify.icons.${isAdmin(member)? 'make_admin' : 'make_moderator'}` }}</v-icon>
                  </v-avatar>
                </div>
                <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-list-item>
            <v-divider
              v-if="(showAllMembers || index < SHOW_MEMBER_LIMIT) && index < members.length - 1"
              :key="index"
            ></v-divider>
          </template>
        </v-list-item-group>
      </v-list>
      <div class="show-all p-2" @click="showAllMembers = !showAllMembers" v-if="members.length > SHOW_MEMBER_LIMIT">
        {{ showAllMembers ? $t("room_info.hide_all") : $t("room_info.show_all") }}
      </div>
    </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>

    <UserProfileDialog
      :show="showMemberActionConfirmation"
      :activeMember="activeMember || members[0]"
      :room="room"
      @close="showMemberActionConfirmation = false"
    />

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

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

    <MessageRetentionDialog
      :show="showMessageRetentionDialog"
      :room="room"
      @close="showMessageRetentionDialog = false"
      v-on:message-retention-update="onMessageRetention"
    />

    <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 MessageRetentionDialog from "../components/MessageRetentionDialog";
import RoomExport from "../components/RoomExport";
import RoomAvatarPicker from "../components/RoomAvatarPicker";
import CopyLink from "../components/CopyLink.vue"
import UserProfileDialog from "./UserProfileDialog.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,
    MessageRetentionDialog,
    UserProfileDialog,
    RoomExport,
    RoomAvatarPicker,
    CopyLink
  },
  data() {
    return {
      members: [],
      user: null,
      showAllMembers: false,
      showMemberActionConfirmation: false,
      showLeaveConfirmation: false,
      showPurgeConfirmation: false,
      showMessageRetentionDialog: false,
      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,
      activeMember: null
    };
  },
  mounted() {
    this.$matrix.on("Room.timeline", this.onEvent);
    this.updateMembers();
    this.updateMessageRetention();
    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();
        this.updateMessageRetention();
      },
    },
  },

  methods: {
    onMessageRetention(retention){
      const retentionPeriodsFound = this.retentionPeriods.find(rp => rp.value===retention)
      this.messageRetentionDisplay = retentionPeriodsFound.text
      },
    onListItemClick(member) {
      this.activeMember = member
      this.showMemberActionConfirmation = true
    },
    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 = [];
      }
    },

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

    /**
     * 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;
        });
    },
    exportRoom() {
      if (this.room) {
        this.exporting = true;
      }
    },
    /**
     * 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;
    },
    /**
     * 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>