<template>
  <div class="chat-list-item">
    <chatAvatar class="for-chat-list-item" :style="avatarBackground">
      {{ avatar.length > 0 ? '' : other_person.name[0] }}
    </chatAvatar>
    <div class="chat-list-item--info">
      <div class="chat-list-item--info-left">
        <div class="chat-list-item--info-left__name"> {{ other_person.name }} </div>
        <div class="chat-list-item--info-left__product"> {{ product_name }} </div>
        <div class="chat-list-item--info-left__purchase-date">
          <template v-if="isPurchase">
            <span class="mdi mdi-basket" v-if="chatInfoStartDate.length > 0"></span>
            Purchased {{ chatInfoStartDate }}
          </template>
          <template v-else>
            <span class="mdi mdi-comment-question" v-if="chatInfoStartDate.length > 0"></span>
            Conversation started {{ chatInfoStartDate }}
          </template>
        </div>
      </div>
      <div class="chat-list-item--info-right">
        <div class="chat-list-item--info-right__last-time">
          {{ chatInfoLastTime }}
        </div>
        <div :class="['chat-list-item--info-right__badge', {'badge': newMessagesCount > 0}]">
          <template v-if="newMessagesCount > 0">
          {{ newMessagesCount }}
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { Component, Prop, Watch, Vue } from 'vue-property-decorator';
  import chatAvatar from './ChatAvatar.vue';
  import ChatEngine from './ChatEngine';
  import moment from 'moment';

  @Component({
    components: {
      chatAvatar,
    },
  })
  export default class ChatListItem extends Vue {
    @Prop() private chatInfo!: any;
    @Prop() private chatEngine!: ChatEngine;

    private chatMeta: any = {};
    private product: any = {};
    private avatar: any = '';
    private avatarBackground: any = {};
    // {
    //   "chats" : [ {
    //     "id" : "0844c1c2-0228-4884-ad02-c1ce45b95030",
    //     "from" : {
    //       "id" : "dc255f9f-a22d-4d4b-aec0-add546bc18fb",
    //       "name" : "Admin"
    //     },
    //     "to" : {
    //       "id" : "cfe665f4-3beb-44e2-9194-dbe8f7e888c4",
    //       "name" : "Ivan"
    //     },
    //     "title" : "",
    //     "startDate" : "2019-07-09T05:39:08"
    //   } ]
    // }

    get other_person(): any {
      // FIXME: this is specific to bessern
      const op = this.$root.getOtherPerson(this.chatInfo.to, this.chatInfo.from);
      console.error('from person', op.id);
      return op || {};
    }

    get other_id(): String {
      this.$root.$api.person().getPerson(this.other_person.id)
      .then((success: any) => {
        try {
          this.avatar = success.data.avatars[0].file.externalName
          this.avatarBackground = {
            'background-image': 'url('+ this.chatEngine.url + '/data/' + this.avatar + '/200x200)'
          };
        } catch(error) {
          this.avatarBackground = {
            'background-color': 'hsla(180,'+Math.floor(Math.random()*90 + 50)+'%,'+Math.floor(Math.random()*50)+'%,1)'
          };
        }
      }).catch((error: any) => {
        this.avatarBackground = {
          'background-color': 'hsla(180,'+Math.floor(Math.random()*90 + 50)+'%,'+Math.floor(Math.random()*50)+'%,1)'
        };
      });
      return this.other_person.id || '';
    }

    get product_name(): any {
      try {
        return this.product.name;
      } catch (error) {
        
      }
    }

    get chatInfoStartDate(): any {
      // return moment.utc(this.chatInfo.startDate).fromNow();
      return moment(this.chatInfo.startDate).fromNow();
    }

    get chatInfoLastTime(): any {
      // return moment.utc(this.chatInfo.lastMessageDate).fromNow();
      return moment(this.chatInfo.lastMessageDate).fromNow();
    }

    get isPurchase(): any {
      return this.chatMeta.type === 'transaction';
    }

    get newMessagesCount(): any {
      // FIXME: this is specific to bessern
      const userId = this.$root.userID;

      // Get the number of unread message for me
      if (userId === this.chatInfo.from.id) {
        return this.chatInfo.party1UnreadCount;
      } else if (userId === this.chatInfo.to.id) {
        return this.chatInfo.party2UnreadCount;
      }
      return -1; // for debug
    }

    private async mounted() {
      try {
        this.chatMeta = JSON.parse(this.chatInfo.meta);
        this.product = (await this.$root.$api.product().getProduct(this.chatMeta.productId)).data;
      } catch(error) {
        
      }
    }

    @Watch('other_id') changed_otherID(x: any, y: any) {
      console.warn('avatarName', this.avatarName);
      this.$root.$api.person().getPerson(x)
      .then((success) => {
        console.warn('userAvatar', success.data);
        // this.avatarName = success.data.avatar[0]
      }).catch((error) => {
        console.error('userAvatar', error);
      });
      console.warn('avatarName', this.avatarName);
    }
  }
</script>

<style lang="scss" scoped>
@import '../../node_modules/@mdi/font/css/materialdesignicons.css';
@import '../styles/partials/index.scss';

.chat-list-item {
  width: 100%;
  height: 90px;
  padding-left: 16px;
  @include css3-prefix(box-sizing, border-box);
  @include css3-prefix(display, flex);
  @include css3-prefix(flex-direction, row);
  @include css3-prefix(align-items, center);
  @include css3-prefix(justify-content, center);

  &.no-border {
    .chat-list-item--info {
      border-bottom: none;
    }
  }

  &--info {
    position: relative;
    max-width: calc(100% - 63px);
    height: 100%;
    padding: 13px 27px 13px 20px;
    border-bottom: solid 1px #979797;
    @include css3-prefix(box-sizing, border-box);
    @include css3-prefix(flex, auto);
    @include css3-prefix(display, flex);
    @include css3-prefix(flex-direction, row);
    @include css3-prefix(align-items, center);
    @include css3-prefix(justify-content, center);

    &-left {
      width: 100%;
      height: 100%;
      @include css3-prefix(flex, auto);
      @include css3-prefix(display, flex);
      @include css3-prefix(flex-direction, column);
      @include css3-prefix(align-items, flex-start);
      @include css3-prefix(justify-content, space-between);

      &__name {
        height: 19px;
        color: #4a4a4a;
        font-size: 16px;
        font-weight: bold;
      }
      &__product {
        width: 100%;
        height: 14px;
        color: #8b8b8b;
        font-size: 11px;
        font-weight: 500;
        line-height: 14px;
        margin-top: 3px;
        white-space: nowrap; 
        overflow: hidden;
        text-overflow: ellipsis;
      }
      &__purchase-date {
        color: #8b8b8b;
        height: 12px;
        font-size: 9px;
        font-weight: 500;
        line-height: 12px;
        margin-top: 3px;

        &.mid.mdi-basket {
          margin-right: 5px;
        }
      }
    }
    &-right {
      position: relative;
      height: 100%;
      width: 70px;
      text-align: right;
      @include css3-prefix(display, flex);
      @include css3-prefix(flex-direction, column);
      @include css3-prefix(align-items, center);
      @include css3-prefix(justify-content, space-between);

      &__last-time {
        position: absolute;
        // top: 13px;
        top: 0;
        // right: 27px;
        right: 0;
        width: 150px;
        height: 19px;
        font-size: 11px;
        font-weight: 500;
        line-height: 19px;
      }

      &__badge {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 19px;
        height: 19px;
        border-radius: 100%;
        font-size: 9px;
        font-weight: 900;
        line-height: 19px;
        text-align: center;
        
        @include css3-prefix(display, flex);
        @include css3-prefix(flex-direction, column);
        @include css3-prefix(align-items, center);
        @include css3-prefix(justify-content, center);

        &.badge {
          color: #ffffff;
          background-color: #00e0c1;
        }
      }
    }
  }
}

</style>