<template>
  <div class="nv-rating__item" :class="customClass">
    <NvIcon
      :icon="currentIcon"
      :style="{ color: value ? color : emptyColor }"
      :size="size"
    />
    <div
      class="nv-rating__mark"
      @mouseenter="onMouseenter(true)"
      @click="onClick(true)"
    ></div>
    <div
      class="nv-rating__mark"
      @mouseenter="onMouseenter(false)"
      @click="onClick(false)"
    ></div>
  </div>
</template>

<script>
import { readonly } from "vue";

export default {
  name: "NvRatingItem",

  props: {
    color: { type: String, required: true },
    customClass: { type: String, required: true },
    emptyColor: { type: String, required: true },
    emptyIcon: { type: String, required: true },
    fullIcon: { type: String, required: true },
    half: Boolean,
    halfIcon: { type: String, required: true },
    hover: Boolean,
    readonly: Boolean,
    value: { type: Number, default: 0 },
    size: { type: String, required: true },
  },

  data: () => {
    return {
      currentIcon: "",
    };
  },

  watch: {
    value() {
      this.setIcon();
    },
  },

  created() {
    this.setIcon();
  },

  methods: {
    onMouseenter(isHalf) {
      if (this.readonly) return;
      if (!this.hover) return;
      this.$emit("onItemHover", isHalf && this.half ? 0.5 : 1);
    },

    onClick(isHalf) {
      if (this.readonly) return;
      this.$emit("onItemClick", isHalf && this.half ? 0.5 : 1);
    },

    setIcon() {
      if (this.value > 0) {
        if (this.value <= 0.5 && this.half) {
          this.currentIcon = this.halfIcon;
        } else {
          this.currentIcon = this.fullIcon;
        }
      } else {
        this.currentIcon = this.emptyIcon;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.nv-rating__item {
  @apply relative px-2;
}

.nv-rating__item {
  @apply cursor-pointer;

  &:active {
    @apply opacity-80;
  }
}

.nv-rating__mark {
  @apply absolute top-0 h-full left-1/2 w-1/2;
}

.nv-rating__mark:nth-child(2) {
  @apply left-0;
}
</style>
