<template>
  <ion-card class="loc-full-width-card">

    <!-- TOP HEADER -->
    <ion-item class="loc-item-header" lines="none">

      <!-- start (avatar) -->
      <ion-avatar class="loc-avatar" slot="start" @click="$emit('userClicked', post.user)" style="background: #666">
        <img :src="post.user.avatar" />
      </ion-avatar>
      
      <!-- middle (name, follow, distance) -->
      <ion-grid>

        <!-- name & follow -->
        <ion-row>
          <ion-col>
            <span 
              class="loc-name" 
              @click="$emit('userClicked', post.user)"
            >{{post.user.nickname}}</span>
            <span 
              v-if="me && !isPreview && post.user.uid !== me.uid && !excludedFeatures.includes('follow')"
              class="follow-button"
              @click="$emit('toggleFollow', post.user)"
            >{{ !isFollowed ? "Follow" : "Unfollow" }}</span>
          </ion-col>
        </ion-row>

        <!-- distance -->
        <ion-row>
          <ion-col class="subinfo">
            <span v-if="(post.distance !== null || post.distance !== false) && isLocationValid" class="distance-info">
              <ion-icon name="pin" class="subinfo-icon" /><span>{{distance}}</span>
            </span>
            <span class="distance-info">
              <ion-icon name="calendar" class="subinfo-icon" /><span>{{datetime}}</span>
            </span>
            <span v-if="!isPreview && post.maxResponses && !recoDate" class="distance-info">
              <ion-icon :name="post.isGroup ?  (post.chat_type === 'forum' ? 'contacts' : 'people') : 'person'" class="subinfo-icon"/>
              <!-- In single chat 13 means unlimited ammount of people can reply, so no need to show 0/13 -->
              <span v-if="post.maxResponses < 100">{{ post.numberOfReplies }}<span v-if="post.maxResponses < 13">/{{ post.maxResponses }}</span></span>
              <span v-else>forum</span>
            </span>
            <span class="loc-bookmark" v-if="!isPreview" @click="onBookmarkToggle()">        
              <font-awesome-icon v-if="post.bookmarked && post.bookmarked.includes(me.uid)" :icon="['fas', 'star']" class="loc-star-icon-active"/>
              <font-awesome-icon v-else :icon="['fas', 'star']" class="loc-star-icon"/>
              <span class="loc-bookmark-num">{{post.bookmarked ? post.bookmarked.length : ''}}</span>
            </span>
          </ion-col>
        </ion-row>

      </ion-grid>

      <!-- end (action buttons) -->
      <!-- <ion-icon v-if="!isPreview" class="more-button" name="more" slot="end" @click="openActionSheet()"></ion-icon> -->
      <b-icon v-if="!isPreview" icon="three-dots" slot="end" class="more-button" @click="openActionSheet()" />
    </ion-item>

    <!-- div class="loc-category" :style="'background-color: '+post.category.color">
      <span class="category-name">{{keyTag}}</span>
    </div>

    <div class="separator" v-if="post.subject" :style="'border-color: '+post.category.color"></div>

    <div class="subject" :style="'background: '+post.category.color" v-if="post.subject">
      <div class="subject-container">
        <span>{{post.subject}}</span>
        <span class="datetime" slot="end">{{datetime}}</span>
      </div>
    </div -->

    <!-- bordered block (images/content) -->
    <div 
      v-if="!excludedFeatures.includes('border')"
      class="image-border" :style="`background-color: ${post.category.color}`"
    ></div>
    <div style="position: relative;">
      <ion-slides 
        v-if="isLoaded && post.images && post.images.length" 
        pager="true" 
        ref="slider"
        :options="sliderOpts"
        class="loc-slides"
        :style="'height: '+slideHeight+'px'" 
        v-on:ionSlideTap="slideTapped($event)">
        <ion-slide v-for="image in post.images" :key="image">
          <img :src="image" />
          <transition name="slide-fade" v-if="isPreview && isLoaded && post.images && post.images.length">
						<ion-icon v-show="showSlideDelBtn" name="trash" class="img-del-button" @click.prevent="sendDeleteRequest"></ion-icon>
					</transition>
        </ion-slide>
      </ion-slides>
    </div>

    <!-- content (if no images) -->
    <div 
      v-if="!(post.images && post.images.length)" 
      class="post-content"
    >

      <!-- subject -->
      <div v-if="post.subject" class="post-subject">{{post.subject}} <span v-if="post.edited && post.tags[0].value !== 'profile'" class="loc-post-edited">(edited)</span></div>

      <!-- description -->
      <div 
        v-if="post.description && post.description.length && post.description.length >= 110"
        v-html="isMoreDescription ? post.description : `${post.description.substring(0, 110)}...`" 
        class="post-description no-bottom-padding">
      </div>
      <span 
        class="link" 
        v-if="post.description && post.description.length && post.description.length >= 110" 
        @click="isMoreDescription = !isMoreDescription">{{isMoreDescription ? 'less' : 'more'}}
      </span>
      <div 
        v-if="post.description && post.description.length && post.description.length < 110" 
        v-html="post.description" 
        class="post-description no-bottom-padding">
      </div>

    </div>
    <div 
      v-if="!excludedFeatures.includes('border')"
      class="image-border bottom"
      :style="`background-color: ${post.category.color}`"
    ></div>

    <!-- edit image buttons (for preview) -->
    <!-- <div v-if="isPreview && isLoaded && post.images && post.images.length" class="image-editor-buttons">
      <span class="add-picture" @click.prevent="$emit('addImage')">
        ADD
      </span>
      <span class="delete-picture" @click.prevent="$emit('deleteImage', currentSlideIndex)">
        DELETE
      </span>
    </div> -->

    <!-- content (if images) -->
    <div 
      v-if="post.images && post.images.length" 
      class="post-content"
      :style="!(post.description && post.description.length) ? 'padding-bottom: 0px;' : ''"
    >

      <!-- subject -->
      <div v-if="post.subject" class="post-subject">{{post.subject}} <span v-if="post.edited && post.tags[0].value !== 'profile'" class="loc-post-edited">(edited)</span></div>

      <!-- description -->
      <div 
        v-if="post.description && post.description.length && post.description.length >= 110"
        v-html="isMoreDescription ? post.description : `${post.description.substring(0, 110)}...`" 
        class="post-description no-bottom-padding">
      </div>
      <span 
        class="link" 
        v-if="post.description && post.description.length && post.description.length >= 110" 
        @click="isMoreDescription = !isMoreDescription">{{isMoreDescription ? 'less' : 'more'}}
      </span>
      <div 
        v-if="post.description && post.description.length && post.description.length < 110" 
        v-html="post.description" 
        class="post-description no-bottom-padding">
      </div>

    </div>

    <!-- tags -->
    <ion-item class="loc-item-tags" v-if="post.tags && post.tags.filter(el => !el.is_recommended).length" lines="none">
        <div style="overflow-x: scroll; height: 36px; margin-left: 4px">
          <div :style="'width: '+getTagContainerWidth()+'; height: 36px'">
            <reco-tag 
              v-for="tag in post.tags.filter(el => !el.is_recommended)" 
              :key="tag.display_name" 
              @click="$emit('toggleTag', tag)" 
              :tag="tag" 
              :category="post.category" 
            />
          </div>
        </div>
    </ion-item>

    <div>
      <div class="loc-category-button" :style="{color: post.category.color}" @click="$emit('categoryButtonClicked', keyTag)">
        {{keyTag.display_name}}
      </div>

      <div class="loc-button-box">

        <div v-if="me && me.uid !== post.user.uid && !post.withNoReplyButton && !post.isInactive && post.user_reply_status == 'none'"
          class="loc-reply-button" 
          @click="$emit('replyButtonClicked', post)">
          {{ post.chat_type === 'forum' ? 'Join' : 'Chat Now' }}
        </div>

        <div v-if="me && me.uid !== post.user.uid && !post.withNoReplyButton && !post.isInactive && post.user_reply_status == 'pending'"
          class="loc-inactive-button">
          Pending
        </div>

        <div v-if="me && me.uid !== post.user.uid && !post.withNoReplyButton && !post.isInactive && post.user_reply_status == 'accepted'"
          class="loc-reply-button" >
          Replied
        </div>

        <div v-if="me && me.uid !== post.user.uid && !post.withNoReplyButton && !post.isInactive && post.user_reply_status == 'denied'"
          class="loc-delete-button" >
          Chat rejected
        </div>

        <div v-if="!me && !isPreview" class="loc-reply-button"  @click="$emit('loginToReplyButtonClicked', post)">
          Log in to Chat
        </div>

        <div v-if="me && me.uid !== post.user.uid && !post.withNoReplyButton && post.isInactive" class="loc-inactive-button">
          <ion-icon class="loc-button-icon" ios="md-time" md="md-time" /> Post Expired
        </div>

        <div v-if="me && me.uid === post.user.uid && !post.withNoReplyButton && post.tags[0].value !== 'profile'" class="loc-delete-button" @click="$emit('deleteButtonClicked', post)">
          <ion-icon class="loc-button-icon" name="trash" /> Delete
        </div>
        <div v-if="me && me.uid === post.user.uid && !post.withNoReplyButton && post.tags[0].value !== 'profile'" class="loc-edit-button" @click="$emit('editButtonClicked', post)">
          <span v-if="post.isInactive">Repost</span><span v-else><b-icon class="loc-button-icon" icon="pencil" /> Edit</span>
        </div>
      </div>
    </div>

  </ion-card>
</template>

<script lang="ts">
import moment from 'moment'
import RecoImg from '@/components/atomic/RecoImg.vue'
import RecoTag from '@/components/atomic/RecoTag.vue'

export default {
  components: {
    RecoImg, RecoTag
  },
  props: {
    post: {
      type: Object,
    },
    me: {
      type: Object,
      default() {
        return null
      }
    },
    following: {
      type: Array,
      default() {
        return []
      }
    },
    isPreview: {
      type: Boolean
    },
    isLocationValid: {
      type: Boolean,
      default: true,
    },
    excludedFeatures: {
      type: Array,
      default() {
        return [];
      }
    },
    recoDate: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      sliderOpts: {
        zoom: {
          maxRatio: 3,
          toggle: true,
        },
        initialSlide: 1, 
        speed: 400,
      },
      isLoaded: true,
      slideHeight: 250,
      isMoreDescription: false,
      showSlideDelBtn: false
    };
  },
  computed: {
    datetime() {
      return moment(this.post.timestamp).fromNow(true)
        .replace('a few seconds', '1sec')
        .replace('a few minutes', '1min')
        .replace('seconds', 'sec')
        .replace('second', 'sec')
        .replace('minutes', 'min')
        .replace('minute', 'min')
        .replace('hours', 'h')
        .replace('hour', 'h')
        .replace('days', 'd')
        .replace('day', 'd')
        .replace('months', 'mo')
        .replace('month', 'mo')
        .replace('an ', '1')
        .replace('a ', '1')
        .replace(' ', '');
    },
    distance() {
      if(this.post.distance < 1) {
        return (Math.round(this.post.distance*100)*10)+"m";
      }
      if(this.post.distance > 10) {
        return Math.round(this.post.distance)+"km";
      }
      return (Math.round(this.post.distance*10)/10)+"km";
    },
    keyTag() {
      if (Array.isArray(this.post.tags)) {
        const keyTags = this.post.tags.filter(el => el.is_recommended);
        if (Array.isArray(keyTags) && keyTags.length) {
          return keyTags[0];
        }
      }
      return {display_name: 'Test topic'};
    },
    isFollowed() {
      return this.following.find(profile => this.post.user.uid == profile.uid) ? true : false;
    }    
  },
  created() {
    this.setSlideHeight();
  },
  methods: {
    slideTapped($event) {
      if(this.isPreview){
        this.showSlideDelBtn = !this.showSlideDelBtn;
      }
      else{
        $event.target.swiper.zoom.toggle();
      }
    },
    getTagContainerWidth() {
      let num_of_tags = this.post.tags.length;
      let letters = 0;
      for (var i = 0; i < num_of_tags; i++) {
        letters += this.post.tags[i].display_name.length;
      }
      return (letters*12+num_of_tags*16)+'px';
    },
    setSlideHeight() {
      if (this.post.image_dimensions && this.post.image_dimensions.length && this.post.image_dimensions[0].width) {
        let dimensions = this.post.image_dimensions[0];
        let screenWidth = screen.width;
        this.slideHeight = ((window.innerWidth / dimensions.width) * dimensions.height)+1;
      }
    },
    openActionSheet() {
      const favText = this.me.bookmarked.includes(this.post.id) ? "Remove Favorite" : "Add Favorite";
      const buttons = [{
        text: favText,
        role: 'none',
        handler: () => {
          this.onBookmarkToggle();
        }
      },
      {
        text: 'Share',
        role: 'none',
        handler: () => {
          this.$emit('shareButtonClicked', this.post);
        },
      }];
      if (this.post.user.uid !== this.me.uid) {
        buttons.push({
            text: 'Report',
            role: 'destructive',
            handler: () => {
              this.openReportModal();
            },
          });
      }
      return this.$ionic.actionSheetController
        .create({ buttons })
        .then(a => a.present())
    },
    openReportModal() {
      return this.$ionic.alertController
        .create({
          header: 'Checkbox',
          inputs: [
            { type: 'checkbox', label: 'Racist', value: 'racist' },
            { type: 'checkbox', label: 'Abusive', value: 'abusive' },
            { type: 'checkbox', label: 'Aggressive', value: 'aggressive' },
            { type: 'checkbox', label: 'Spam', value: 'spam' },
            { type: 'checkbox', label: 'Other', value: 'other' },
          ],
          buttons: [
            {
              text: 'Cancel',
              role: 'cancel',
              cssClass: 'secondary',
            },
            {
              text: 'Report',
              handler: response => {
                this.$emit("reported", {post: this.post, response});
              },
            },
          ],
        })
        .then(a => a.present())
    },
    updateSlider() {
      console.log('IMAGES: ', this.post.images);
      // this.$refs.slider.update();
      this.isLoaded = false;
      setTimeout(() => {
        this.isLoaded = true;
      }, 100);
    },
    slideToEnd() {
      this.$refs.slider.slideTo(this.post.images.length);
    },
    onBookmarkToggle(){
      this.$emit('bookmarkToggle', this.post);
    },
    async sendDeleteRequest(){
      const activeIndex = await this.$refs.slider.getActiveIndex();
      this.$emit('deleteImage', activeIndex);
    }
  },
}
</script>

<style scoped lang="css">
  .link {
    font-weight: bold;
    color: var(--reco-link-color);
  }
  .loc-full-width-card {
    position: relative;
    margin: 0;
    border-radius: 0px;
    position: relative;
    box-shadow: 0px 0 10px rgba(0,0,0,0.2);
  }
  .loc-slides {
    position: relative;
    z-index: 11;
    border-bottom: 1px solid #ccc;
    width: 100%;
    --bullet-background: var(--actiways-primary-color);
    --bullet-background-active: var(--actiways-primary-color);
  }
  .loc-avatar {
    margin-top: 6px;
    margin-bottom: 6px;
    margin-right: 4px;
    margin-left: 0;
    width: 46px;
    height: 46px;
  }
  .loc-name {
    display: inline-block;
    margin-right: 10px;
    font-weight: bold;
    font-size: 15px;
  }
  .follow-button {
    display: inline-block;
    font-size: 15px;
    font-weight: bold;
    color: var(--reco-link-color);
  }
  .subinfo {
    padding: 0px 0px 6px 0;
    font-size: 13px;
    color: rgba(0,0,0,0.75);
  }
  .subinfo .subinfo-icon {
    font-size: 15px;
    margin-right: 4px;
    position: relative;
    top: 2px;
  }
  .subinfo .distance-info {
    display: inline-block;
    margin-right: 10px;
  }
  .image-border {
    height: 8px;
  }
  .image-border.bottom {
    position: relative;
    top: -1px;
    z-index: 100;
  }
  .post-content {
    padding: 6px 12px 12px 12px;
  }
  .post-content .post-subject {
    color: rgba(0,0,0,.92);
    font-size: 22px;
    padding: 8px 0 8px 0;
    font-weight: bold;
  }
  .post-content .post-description {
    color: rgba(0,0,0,.84);
    font-size: 15px;
    line-height: 20px;
    padding-bottom: 8px;
  }
  .post-content .post-description.no-bottom-padding {
    padding-bottom: 0px;
  }
  .loc-button-box {
    width: 100%;
  }
  .loc-inactive-button,
  .loc-delete-button,
  .loc-edit-button,
  .loc-reply-button {
    font-size: 17px;
    float: right;
    line-height: 32px;
    border-radius: 8px;
    text-transform: uppercase;
    font-weight: bold;
    margin: 10px;
  }
  .loc-delete-button,
  .loc-edit-button,
  .loc-reply-button:active{
    position: relative;
    top: 2px;
  }
  .loc-delete-button {
    color: #e84118;
  }
  .loc-edit-button{
    color:var(--ion-color-primary-tint);
  }
  .loc-inactive-button {
    color: #7f8fa6;
  }
  .reply-type-info {
    float: left;
    line-height: 32px;
    margin: 10px;
    font-size: 14px;
    color: #666;
    font-weight: bold;
  }
  .reply-type-info .subinfo-icon {
    position: relative;
    top: 4px;
    font-size: 18px;
    padding-right: 2px;
  }
  .loc-chip-default {
    border-width: 1px !important;
    border-color: rgba(0,0,0,0.76) !important;
    color: rgba(0,0,0,0.76) !important;
    padding: 4px 9px !important;
    height: 30px;
  }
  .loc-chip-success {
    font-weight: 500;
    border-width: 2px !important;
    border-color: rgba(0,0,0,0.76) !important;
    color: rgba(0,0,0,0.76) !important;
    padding: 4px 9px !important;
    height: 28px;
  }
  .loc-item-header {
    --padding-start: 10px;
    --padding-end: 0px;
    --inner-padding-end: 0px;
  }
  .loc-item-tags {
    --padding-start: 6px;
    --padding-end: 6px;
  }
  .loc-icon {
    font-size: 17px !important;
    position: relative;
    right: 1px;
  }
  .image-editor-buttons {
    padding: 10px 10px 0 10px;
    font-weight: 700;
    font-size: 17px;
    text-align: right;
  }
  .loc-button-icon {
    position: relative;
    right: 3px;
    top: 3px;
    font-size: 18px;
  }
  .image-editor-buttons .delete-picture {
    display: inline-block;
    color: #c0392b;
    margin-left: 12px;
  }
  .image-editor-buttons .add-picture {
    display: inline-block;
    color: #2980b9;
  }

  .subject-container {
    display:flex;
    align-items: center;
  }

  .subject-container span {
    width: 90%;
  }

  .post-type-icon {
    position: relative;
    bottom: 3px;
    display: inline-block;
    width: 24px;
    height: 24px;
    line-height: 24px;
    border-radius: 14px;
    text-align: center;
    font-size: 15px;
    background: #fff;
    margin-left: 6px;
  }

  .post-type-icon .type-icon {
    position: relative;
    right: 1px;
    top: 1px;
  }

  .loc-category-button{
    float: left;
    font-size: 17px;
    line-height: 32px;
    text-transform: uppercase;
    font-weight: bold;
    margin: 10px;
  }
  .loc-category-button:active{
    position: relative;
    top: 2px;
  }
  .loc-reply-button{
    color: var(--actiways-primary-color);
  }
  .slide-fade-enter-active {
    transition: all .5s ease;
  }
  .slide-fade-leave-active {
    transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  }
  .slide-fade-enter, .slide-fade-leave-to {
    transform: translateX(10px);
    opacity: 0;
  }
  
.img-del-button{
	position: absolute;
  top: 10px;
  right: 10px;
 	background-color: var(--actiways-primary-color);
	color: white;
  padding: 3px 6px;
 	border: none;
  cursor: pointer;
  border-radius: 5px;
  text-align: center;
	font-size: 1.5em;
}
.loc-bookmark{
}
.loc-star-icon{
  font-size: 15px;
}
.loc-star-icon-active{
  font-size: 15px;
  color: #ffcc6f;
}
.loc-bookmark-num{
  margin-left: 2px;
}
.more-button{
  padding-right: 5px;
  font-size: 34px;
}
.loc-post-edited{
  font-size: 12px;
  color: var(--reco-lighter-font-color);
  font-weight: normal;
}
</style>
<style lang="css">
.post-content .post-description.no-bottom-padding p{
  margin: 0;
}
.post-content .post-description.no-bottom-padding ul, ol{
  margin: 5px;
}
</style>
