<template>
  <span ref="wrapper" class="rating" @click="handleClick" @mousemove="handleMousemove" @mouseleave="handleMouseleave">
    <span class="set empty-set">
      <app-icon v-for="i in starCount" icon="star"></app-icon>
    </span>
    <span class="set filled-set" :style="filledStyle">
      <app-icon v-for="i in starCount" icon="star"></app-icon>
    </span>
  </span>
</template>

<script>

  import AppIcon from "./AppIcon";

  export default {
    props: {
      starCount: {
        required: false,
        type: Number,
        default: 5
      },
      rating: {
        required: false,
        type: Number,
        default: 0
      }
    },

    data() {
      return {
        temporaryWidth: null
      };
    },

    computed: {
      ratingPercent() {
        return (this.rating / this.starCount) * 100.0;
      },

      filledStyle() {
        const width = this.temporaryWidth === null ? this.ratingPercent : this.temporaryWidth;
        return {
          width: width + "%"
        };
      }
    },

    methods: {
      handleClick(evt) {
        console.log("click");
      },

      handleMousemove(evt) {
        const wrapperBox = this.$refs.wrapper.getBoundingClientRect();
        const wrapperWidth = wrapperBox.right - wrapperBox.left;
        const mousePosition = evt.clientX;

        if (mousePosition > wrapperBox.left && mousePosition < wrapperBox.right) {
          this.temporaryWidth = ((mousePosition - wrapperBox.left) / wrapperWidth) * 100.0;
        }
      },

      handleMouseleave(evt) {
        this.temporaryWidth = null;
      }
    },

    components: {
      AppIcon
    }
  }

</script>

<style lang="scss" scoped>

  span.rating {
    position: relative;
    display: inline-block;

    .set {
      white-space: nowrap;
    }

    .empty-set {
      color: gray;
    }

    .filled-set {
      color: gold;
      position: absolute;
      top: 0;
      left: 0;
      overflow-x: hidden;
    }
  }

</style>