<template>
  <div 
    :class="['chat--message', 
              mine? 'message-is-mine' : 'message-is-other',
              'message-' + this.message.status,
              'message-' + this.message.type]"
    :data-message-id="message.id"
    :data-message-mine="mine"
    v-observe-visibility="visibilityChanged"
  >
    <component
        :chatEngine=chatEngine
        :bus=bus
        v-bind:is="componentName"
        :key="message.id"
        :message="message"
    />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { Message } from './type';

import MessageText from './MessageText.vue';
import MessageAudio from './MessageAudio.vue';
import MessageImage from './MessageImage.vue';
import MessageDocument from './MessageDocument.vue';
import MessagePurchase from './MessagePurchase.vue';
import MessageOffer from './MessageOffer.vue';
import MessageCompleteRequest from './MessageCompleteRequest.vue';

import Chat from './Chat.vue';
import ChatEngine from './ChatEngine';

@Component({
  components: {
    MessageText,
    MessageAudio,
    MessageImage,
    MessageDocument,
    MessagePurchase,
    MessageOffer,
    MessageCompleteRequest,
  },
})
export default class MessageBase extends Vue {
  // The Chat engine
  @Prop() private chatEngine!: ChatEngine;

  // The event bus
  @Prop() private bus!: Chat;

  // The message data
  @Prop() private message!: Message;

  // Is this a message from the current user
  @Prop() private mine!: boolean;

  // Name of the component used to render the message
  private componentName!: string;

  // Map of message types to components
  private componentsMap = {
    text: 'MessageText',
    image: 'MessageImage',
    audio: 'MessageAudio',
    document: 'MessageDocument',
    purchase: 'MessagePurchase',
    offer: 'MessageOffer',
    complete_request: 'MessageCompleteRequest',
  };

  get timestamp() {
    const timestamp = this.message.timestamp || '';
    const regex = /(\d\d:\d\d):\d\d/g;
    const result = regex.exec(timestamp);
    return result ? result[1] : '';
  }

  public visibilityChanged(isVisible: boolean, entry: any) {
    console.info('Visibility changed');
    if (isVisible && !this.mine) {
      console.info('[Chat.MessageBase] Mark message as read m:' + this.message.id);
      this.chatEngine.markAsRead(this.bus.chatId, this.message);
    }
  }

  // When the component is created, figure out which
  //   component is used to render the message
  public created() {
    if (this.message.type in this.componentsMap) {
      this.componentName = (this.componentsMap as any)[this.message.type] as string;
    } else {
      this.componentName = this.componentsMap.text;
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

</style>
