<template>
  <div class="rooms">
    <div
      v-for="room in $matrix.state.rooms"
      :key="room.id"
      :class="{ active: room.roomId === currentRoomId }"
      class="room"
      @click="$emit('click-on-room', room)">
      <div class="avatar">
        <avatar
          shape="square"
          icon="md-people"
          size="large" />
      </div>
      <div class="room-info">
        <header>
          <span>{{ room.name }}</span>
        </header>
        <p>
          <template v-if="room.timeline.length">
            {{ getEventContent(room.timeline[room.timeline.length - 1].event) }}
          </template>
          <template v-else>
            -
          </template>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    currentRoomId: {
      type: String,
      default: null
    },
    sortByLastActivity: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    if (this.$matrix.client.clientRunning) {
      this.init();
    }

    this.$matrix.event.$on("prepared", () => {
      this.init();
    });
  },
  methods: {
    init() {
      // handle room leaving
      this.$matrix.event.$on("left-room", room => {
        const roomIndex = this.$matrix.state.rooms.findIndex(
          r => r.roomId === room.roomId
        );

        if (roomIndex > -1) {
          this.$emit("close-room");
        }
      });
    },
    getRoomAvatar(room) {
      return room.getAvatarUrl(this.$matrix.client.getHomeserverUrl());
    },

    getEventContent(event) {
      if (event.type === "m.room.message") {
        if (event.content.msgtype === "m.text") {
          return event.content.body;
        }
        return "message";
      }
      return "-";
    }
  }
};
</script>

<style lang="less" scoped>
@border-color-base: #dddee1;
@background-color-select-hover: #dddee1;
@primary-color: #2d8cf0;

.rooms {
  width: 100%;

  .room {
    width: 100%;
    display: inline-flex;

    &:hover {
      cursor: pointer;
      background-color: @background-color-select-hover;
    }

    &.active {
      border-right: 2px solid @primary-color;

      .room-info {
        color: @primary-color;
      }
    }

    .avatar {
      padding: 12px 16px;
      display: inline-block;
    }

    .room-info {
      padding: 12px 0;
      width: calc(~'100% - 75px');
      display: inline-block;

      header {
        span {
          font-weight: bold;
        }
      }

      p {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
    }
  }
}
</style>
