<template>
  <div class="messages-list-scroll">
    <scroll
      id="messages-scroll"
      height="100%"
      :on-reach-top="onReachTop">
      <div id="messages-wrapper">
        <div class="messages">
          <div
            v-for="event in currentRoom.getLiveTimeline().getEvents()"
            v-if="!(event.getType() === 'm.room.power_levels' || event.getType() === 'm.room.join_rules'
                   || event.getType() === 'm.room.history_visibility')"
            :key="event.getId()"
            class="message">
            <avatar
              shape="square"
              icon="md-person"
              class="avatar" />
            <div class="message-body">
              <div class="message-header">
                <span v-if="event.sender"
                      class="message-sender-name">
                  <template v-if="event.getType() === 'm.room.create'">
                    {{ currentRoom.getMember(event.getContent().creator).name }}
                  </template>
                  <template v-else>
                    {{ event.sender.name }}
                  </template>
                </span>
                <span class="message-datetime">{{ event.getDate() | datetime }}</span>
              </div>
              <template v-if="event.getType() === 'm.room.message' && event.getContent().msgtype === 'm.image'
                              && event.getContent().info">
                <img :src="$matrix.client.mxcUrlToHttp(event.getContent().info.thumbnail_url)">
              </template>
              <p>
                <template v-if="event.getType() === 'm.room.message'">
                  {{ event.getContent().body }}
                  <template v-if="event.getContent().msgtype === 'm.image' || event.getContent().msgtype === 'm.file'">
                    <img :src="$matrix.client.mxcUrlToHttp(event.getContent().url)"/>
                    <a :href="$matrix.client.mxcUrlToHttp(event.getContent().url)" target="_blank">Download</a>
                  </template>
                </template>
                <template v-else-if="event.getType() === 'm.room.member'">
                  <tag
                    v-if="event.getContent().membership === 'join'"
                    color="green">
                    Joined
                  </tag>
                  <tag
                    v-else-if="event.getContent().membership === 'invite'"
                    color="default">
                    Invited {{ event.getContent().displayname }}
                  </tag>
                  <tag
                    v-else-if="event.getContent().membership === 'leave'"
                    color="red">
                    Left
                  </tag>
                </template>
                <template v-else-if="event.getType() === 'm.room.name'">
                  <tag>Change room name to {{ event.getContent().name }}</tag>
                </template>
                <template v-else-if="event.getType() === 'm.room.create'">
                  <tag>Created room</tag>
                </template>
                <template v-else>
                  type: {{ event.getType() }}, content: {{ event.getContent() }}
                </template>
              </p>
            </div>
          </div>
        </div>
      </div>
    </scroll>
  </div>
</template>

<script>
export default {
  filters: {
    datetime: function datetime(value) {
      const month = `00${value.getMonth() + 1}`.substr(-2);
      const date = `00${value.getDate()}`.substr(-2);
      const hour = `00${value.getHours()}`.substr(-2);
      const minute = `00${value.getMinutes()}`.substr(-2);
      return `${value.getFullYear()}-${month}-${date} ${hour}:${minute}`;
    }
  },
  props: {
    currentRoomId: {
      type: String,
      default: null
    }
  },
  computed: {
    currentRoom() {
      return this.$matrix.client.getRoom(this.currentRoomId);
    }
  },
  watch: {
    currentRoomId() {
      this.scrollToEnd();
    }
  },
  mounted() {
    const connectCallback = () => {
      this.$matrix.client.on(
        "Room.timeline",
        (event, room, toStartOfTimeline, removed, data) => {
          if (
            !toStartOfTimeline &&
            data.liveEvent &&
            event.getSender() === this.$matrix.client.getUserId()
          ) {
            this.scrollToEnd();
          }
        }
      );
    };
    if (this.$matrix.client === null) {
      this.$matrix.event.$on("prepared", () => {
        this.scrollToEnd();
        connectCallback();
      });
    } else {
      this.scrollToEnd();
      connectCallback();
    }
  },
  methods: {
    getSenderAvatarUrl(event) {
      if (!event.sender) {
        return "";
      }
      return event.sender.getAvatarUrl(this.$matrix.client.getHomeserverUrl());
    },
    onReachTop() {
      return this.$matrix.client.scrollback(this.currentRoom);
    },
    scrollToEnd() {
      this.$nextTick(() => {
        const containerWrapper = document.getElementById("messages-scroll");
        if (containerWrapper !== null) {
          const container = containerWrapper.getElementsByClassName(
            "ivu-scroll-container"
          )[0];

          if (container !== null) {
            container.scrollTop = container.scrollTopMax;
          }
        }

        const eventsLength = this.currentRoom.getLiveTimeline().getEvents()
          .length;
        if (eventsLength > 0) {
          this.$matrix.client.sendReadReceipt(
            this.currentRoom.getLiveTimeline().getEvents()[eventsLength - 1]
          );
        }
      });
    }
  }
};
</script>

<style lang="less">
#messages-scroll {
  .ivu-scroll-container {
    height: 100%;
  }
}
#messages-wrapper {
  .messages {
    max-width: 800px;
    margin: 0 auto;

    .message {
      display: inline-flex;
      width: 100%;
      margin: 0 auto 16px auto;
      max-width: 1000px;
      padding: 0 15px;
      
      .avatar {
        margin-right: 16px;
      }
      .message-body {
        width: 100%;
        .message-header {
          * {
            display: inline;
          }

          .message-sender-name {
            font-weight: bold;
          }

          .message-datetime {
            float: right;
          }
        }
      }
    }
  }
}
</style>

<style lang="less">
 .messages-list-scroll {
   height: calc(~'100% - 215px');

   & > div {
     height: 100% !important;
   }
 }
</style>

