<template>
  <div class="likes" :class="{ 'likes_liked': userLikedProp }">
    <span>{{ likesProp }}</span><span class="likes__like" @click="addLike"
                                      v-bind="{ 'data-popup': $root.store.user.id ? '' : '.js-popup-auth' }">
    <svg class="likes__icon icon icon-like">
      <use v-bind="{'xlink:href': $root.store.staticUrl + 'img/sprite.svg' + '#icon-like' }"></use>
    </svg></span>
  </div>
</template>

<script>
  import {api} from "../../js/modules/api";
  import {showNotification} from "../../js/modules/notification";

  export default {
    name: 'likes',
    props: ['likes', 'userLiked', 'objType', 'objId'],
    data() {
      return {
        likesProp: +this.likes || 0,
        userLikedProp: this.userLiked || false,
      }
    },
    methods: {
      addLike(event) {
        this.$emit('like');
        if(this.userLikedProp){
          return;
        }
        if(this.$root.store.user.id) {
          event.stopPropagation();
          api.post('/api/v1/likes/', {
            user: this.$root.store.user.id, // FIXME
            obj_type: this.objType,
            obj_id: this.objId,
          }, {
            headers: {
              'Authorization': `Token ${this.$root.store.accessToken}`,
            }
          })
          .then(response => {
            if (response.data && response.data.id) {
              this.userLikedProp = true;
              this.likesProp += 1;
              this.$emit('liked');
            }
          })
          .catch(({response}) => {
            if(response.status == 400 && response.data.error){
              showNotification('error', response.data.error);
            }
          });
        }
      }
    }
  }
</script>

<style>
  .likes {
    font-weight: bold;
    text-align: right;
  }

  .likes__like {
    cursor: pointer;
    margin-left: 5px;
  }

  .likes_liked .likes__like {
    cursor: default;
  }

  .likes__icon {
    margin-bottom: -3px;
  }

  .likes_liked .likes__icon {
    fill: #d40700;
  }
</style>
