<template>
  
  <div :id="rowId" :class="rowClasses" :style="backgroundImageStyle" v-if="!hideComponent">
    <div class="detailed_images">
      <div class="title-paragraph" :class="{ 'animated fadeIn': !!waypointTriggered }">
        <h1 class="title" v-html="properties['Title'].value" v-if="properties['Title'].value"></h1>
        <p class="paragraph" v-html="properties['Paragraph Text'].value" v-if="properties['Paragraph Text'].value"></p>
      </div>
      <div class="images-container" :class="{ 'circle-hovered': !!circleHovered }" :style="'padding-top: ' + currentImageAspectRatioAdjustment + '%;'" v-if="!!computedImagesDetails">
        <div class="icon-container backward" @click="previous" v-if="!hideControls && currentImageIndex > 0">
          <i class="far fa-redo"></i>
        </div>
        <div class="image-container" :class="{ visible: i === currentImageIndex, skip: !!set.skip }" v-for="(set, i) in computedImagesDetails">
          <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" :viewBox="'0 0 ' + set['Image'].value.width + ' ' + set['Image'].value.height" @click="svgClicked" >
            <defs>
              <filter :id="'shadow' + rowIndex" class="shadow" x="-100%" y="-100%" height="300%" width="300%">
                <feGaussianBlur in="SourceAlpha" stdDeviation="9" />
                <feOffset dx="0" dy="8" />
                <feMerge>
                  <feMergeNode />
                  <feMergeNode in="SourceGraphic" />
                </feMerge>
              </filter>
            </defs>
            <image :width="set['Image'].value.width" :height="set['Image'].value.height" :xlink:href="set['Image'].value.url">
            </image>
            <g class="shape-group" :class="'shape-group-' + n" v-for="n in 5">
              <g class="circle-group" :class="{ 'animated fadeIn': !!set['animate ' + n] }" @mouseover="circleHovered = true" @mouseout="circleHovered = false" @click="circleClicked(i, n)">
                <circle class="big-circle" :cx="set['X' + n].value" :cy="set['Y' + n].value" :r="bigCircleRadius" :filter="'url(#shadow' + rowIndex + ')'" v-if="!!set['X' + n].value && !!set['Y' + n].value" />
                <circle class="medium-circle" :cx="set['X' + n].value" :cy="set['Y' + n].value" :r="mediumCircleRadius" v-if="!!set['X' + n].value && !!set['Y' + n].value" />
                <circle class="small-circle" :cx="set['X' + n].value" :cy="set['Y' + n].value" :r="smallCircleRadius" v-if="!!set['X' + n].value && !!set['Y' + n].value" />
                <circle class="transparent-circle" :cx="set['X' + n].value" :cy="set['Y' + n].value" r="30" v-if="!!set['X' + n].value && !!set['Y' + n].value" />
              </g>
              <line
                  :x1="set['X' + n].value"
                  :y1="set['Y' + n].value"
                  :x2="set['DX' + n].value"
                  :y2="set['DY' + n].value"
                  :style="(!isIE) ? 'stroke-dasharray: ' + set['lineLength ' + n] + '; stroke-dashoffset: ' + set['lineLength ' + n] + ';' : ''"
                  v-if="!!set['X' + n].value && !!set['Y' + n].value && !!set['DX' + n].value && !!set['DY' + n].value" />
              <g class="text-group" :class="{ right: set['descRight ' + n] === 1 }">
                <text class="label"
                      :x="Number(set['DX' + n].value) - (set['descRight ' + n] * 300)"
                      :y="Number(set['DY' + n].value)"
                      :data-y="Number(set['DY' + n].value)"
                      v-if="!!set['DX' + n].value && !!set['DY' + n].value">
                  {{ set['Label ' + n].value }}
                </text>
                <text class="description"
                      :x="Number(set['DX' + n].value) - (set['descRight ' + n] * 300)"
                      :y="Number(set['DY' + n].value)"
                      :data-y="Number(set['DY' + n].value)"
                      v-html="line"
                      v-for="(line, j) in set['descArray ' + n]"
                      v-if="!!set['DX' + n].value && !!set['DY' + n].value && !!set['descArray ' + n]">
                </text>
              </g>
            </g>
          </svg>
        </div>
        <div class="icon-container forward" @click="forward" v-if="!hideControls && currentImageIndex < computedImagesDetails.length - 1">
          <i class="far fa-undo"></i>
        </div>
      </div>
      <div class="details-container" v-if="showDetailsSet > -1 && showDetailsNumber > -1">
        <div class="icon-container close" @click="closeModal">
          <i class="far fa-times"></i>
        </div>
        <template v-for="(set, i) in computedImagesDetails" v-if="showDetailsSet === i">
          <div class="details" v-for="n in 5" v-if="showDetailsSet === i && showDetailsNumber === n">
            <div class="label">{{ set['Label ' + n].value }}</div>
            <div class="description" v-html="set['Description ' + n].value"></div>
          </div>
          <div class="controls-container angle--top-left">
            <div class="controls" :class="{ 'both-showing': showDetailsNumber > 1 && showDetailsNumber !== set['points'][set['points'].length-1] }" v-if="showDetailsSet === i && set['points'].length > 1">
              <div class="icon-container previous" @click="showDetailsNumber--" v-if="showDetailsNumber > 1">
                <i class="fas fa-caret-left"></i>
              </div>
              <div class="icon-container next" @click="showDetailsNumber++" v-if="showDetailsNumber !== set['points'][set['points'].length-1]">
                <i class="fas fa-caret-right"></i>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>

</template>

<script>
  export default {
    name: "BuildableDetailedImages",
    props: ['componentData', 'rowClasses', 'rowIndex', 'rowId', 'backgroundImageStyle'],
    data() {
      let hardCodedData = {
        currentImageIndex: 0,
        bigCircleRadius: 16,
        mediumCircleRadius: 10,
        smallCircleRadius: 5,
        transparentCircleRadius: 80,
        labelFontSize: 20,
        descriptionFontSize: 18,
        showDetailsSet: -1,
        showDetailsNumber: -1,
        hideControls: false,
        circleHovered: false,
        waypointTriggered: false,
        isIE: window.navigator.userAgent.indexOf("MSIE ") > 0
      };
      let componentData = JSON.parse(this.componentData);
      return {...hardCodedData, ...componentData};
    },
    mounted() {
      const self = this;
      
      jQuery(window).on("load resize", this.handleResize);

      let waypoint = new Waypoint({
        element: this.$el,
        handler: function() {
          self.waypointTriggered = true;
        },
        offset: "75%"
      });
      
      if (!this.isIE) {
        jQuery(".detailed_images .images-container .image-container svg .shape-group line").on("animationend", function() {
          jQuery(this).next(".text-group").addClass("animated fadeIn").css("visibility", "visible");
        });
      }

      jQuery(".detailed_images .images-container .image-container svg .shape-group .circle-group").on("mouseout", function() {
        jQuery(this).siblings(".text-group").removeClass("animated fadeIn").css("visibility", "hidden");
      });
    },
    beforeDestroy() {
      jQuery(window).off("load resize", this.handleResize);
    },
    computed: {
      hideComponent() {
        return (window.innerWidth < 800 && this.rowClasses.indexOf("hide-mobile") > -1) || (window.innerWidth >= 800 && this.rowClasses.indexOf("hide-desktop") > -1);
      },
      computedImagesDetails() {
        const self = this;
        if (!!this.properties && !!this.properties['Images & Details']) {
          let returnProperties = _.cloneDeep(this.properties['Images & Details']);

          returnProperties.forEach( function(set) {
            set['points'] = [];
            
            for (let i = 1; i <= 5; i++) {
              set['animate ' + i] = self.waypointTriggered;
              
              set['descArray ' + i] = (!!set['Description ' + i].value) ? set['Description ' + i].value.split('\n') : null;
              set['descRight ' + i] = (set['DX' + i].value > (set['Image'].value.width / 2)) ? 1 : 0;
              
              if ((typeof set['X' + i].value !== 'undefined' && set['X' + i].value !== "") && (typeof set['Y' + i].value !== 'undefined' && set['Y' + i].value !== "")) {
                set['points'].push(i);
              }
              
              set['lineLength ' + i] = Math.sqrt(Math.pow((set['DX' + i].value - set['X' + i].value), 2) + Math.pow((set['DY' + i].value - set['Y' + i].value), 2));
            }
            
            set.skip = set['points'].length === 0;
          });
          
          return returnProperties;
        }
      },
      currentImageAspectRatioAdjustment() {
        if (!!this.computedImagesDetails && this.computedImagesDetails.length > 0) {
          let currentImageDetails = this.computedImagesDetails[this.currentImageIndex];
          let height = currentImageDetails['Image'].value.height;
          let width = currentImageDetails['Image'].value.width;
          return (height / width) * 100;
        }
      }
    },
    methods: {
      handleResize() {
        const self = this;
        let lastElementHeight = 0;
        let lastDefinedHeight = 0;
        jQuery(".detailed_images-row:visible").each( function(n, row) {
          jQuery(row).find(".detailed_images .images-container .image-container svg").each( function(i, svg) {
            if (jQuery(svg).find("image").length > 0) {
              let svgElementHeight = lastElementHeight = (svg.getBoundingClientRect().height > 0) ? svg.getBoundingClientRect().height : lastElementHeight;
              let svgDefinedHeight = lastDefinedHeight = (svg.getBBox().height > 0) ? svg.getBBox().height : lastDefinedHeight;
              let percentChange = (svgDefinedHeight - svgElementHeight) / svgDefinedHeight;
              let adjustment = (1 / (1 - percentChange));

              let adjustedLabelFontSize = self.labelFontSize * adjustment;
              let adjustedDescriptionFontSize = self.descriptionFontSize * adjustment;
              let adjustedBigCircleRadius = self.bigCircleRadius * adjustment;
              let adjustedMediumCircleRadius = self.mediumCircleRadius * adjustment;
              let adjustedSmallCircleRadius = self.smallCircleRadius * adjustment;
              let adjustedTransparentCircleRadius = self.transparentCircleRadius * adjustment;

              jQuery(svg).find("g.shape-group").each(function(j, shapeGroup) {
                jQuery(shapeGroup).find("g.circle-group circle.big-circle").attr("r", adjustedBigCircleRadius);
                jQuery(shapeGroup).find("g.circle-group circle.medium-circle").attr("r", adjustedMediumCircleRadius);
                jQuery(shapeGroup).find("g.circle-group circle.small-circle").attr("r", adjustedSmallCircleRadius);
                jQuery(shapeGroup).find("g.circle-group circle.transparent-circle").attr("r", adjustedTransparentCircleRadius);

                jQuery(shapeGroup).find("g.text-group text").each(function(k, text) {
                  let startY = jQuery(text).data("y");
                  if (jQuery(text).hasClass("label")) {
                    jQuery(text).css("font-size", adjustedLabelFontSize + "px");

                    jQuery(text).attr("y", Number(startY) + adjustedLabelFontSize + 10);
                  }
                  else {
                    jQuery(text).css("font-size", adjustedDescriptionFontSize + "px");
                    jQuery(text).attr("y", Number(startY) + adjustedLabelFontSize + 10 + (k * (adjustedDescriptionFontSize * 1.4)));
                  }
                });
              });

              jQuery(svg).find("g.shape-group g.text-group.right").each( function(j, textGroup) {
                let lineX2 = jQuery(textGroup).prev("line").attr("x2");
                let textGroupWidth = textGroup.getBBox().width;

                jQuery(textGroup).find("text").each( function(k, text) {
                  jQuery(text).attr("x", lineX2 - textGroupWidth);
                });
              });
            }
          });
        });
      },
      circleClicked(setIndex, n) {
        if (jQuery(window).width() < 1024) {
          this.showDetailsSet = setIndex;
          this.showDetailsNumber = n;
          jQuery("body").addClass("modal-open");
        }
      },
      closeModal() {
        this.showDetailsSet = -1;
        this.showDetailsNumber = -1;
        jQuery("body").removeClass("modal-open");
      },
      previous() {
        const self = this;
        this.currentImageIndex--;
        this.showDetailsSet = -1;
        this.showDetailsNumber = -1;
        this.hideControls = true;

        if (!!this.computedImagesDetails[this.currentImageIndex].skip && this.currentImageIndex > 0) {
          setTimeout( function() {
            self.previous();
          }, 80);
        }
        else {
          this.hideControls = false;
        }
      },
      forward() {
        const self = this;
        this.currentImageIndex++;
        this.showDetailsSet = -1;
        this.showDetailsNumber = -1;
        this.hideControls = true;
        
        if (!!this.computedImagesDetails[this.currentImageIndex].skip && this.currentImageIndex < this.computedImagesDetails.length - 1) {
          setTimeout( function() {
            self.forward();
          }, 80);
        }
        else {
          this.hideControls = false;
        }
      },
      svgClicked() {
        if (jQuery(window).width() >= 1024) {
          if (this.currentImageIndex < this.computedImagesDetails.length - 1) {
            this.forward();
          }
          else {
            this.previous();
          }
        }
      }
    }
  }
</script>

<style scoped>

</style>