<template>
    <div class="container-fluid shadow rounded-3 p-2 position-relative make-tall">
        <funnelHeader ref="funnelHeader" />
        <vehicleBanner ref="vehicleBanner" :displayGenericVehicleImage=false />
        <funnelSubHeader ref="funnelSubHeader" />
        <damageLocationQuestion
          ref="damageLocation"
          v-model="selectedDamageLocations"
          groupName="DamageLocationQuestion"
        />
        <windshieldOptions
          ref="windshieldOptions" 
          v-model="selectedWindshieldOptions" 
          :selectedDamageLocations="selectedDamageLocations"
        />
        <sideDoorOptions 
          ref="sideDoorOptions"
          groupName="SideDoorSideQuestion"
          v-model="sideDoorOptionsData"
          :selectedDamageLocations="selectedDamageLocations"
        />
        <replaceOptionsQuestion
          ref="backGlassOptions"
          :isAvailable="isRearWindowDamageLocation"
          v-model="selectedRearReplaceOptions"
          groupName="BackGlassReplaceOptionsQuestion"
        />
        <funnelFooter ref="funnelFooter" @back-clicked="backButtonAction" @ForwardClicked="forwardButtonAction" />
    </div>
</template>

<script>
// Components
import funnelHeader from "@/common-components/funnel-header/funnel-header";
import funnelFooter from "@/common-components/funnel-footer/funnel-footer";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
import funnelSubHeader from "@/common-components/funnel-sub-header/funnel-sub-header";
import sideDoorOptions from "@/layouts/vehicle-damage/side-door-options/side-door-options";
import damageLocationQuestion from "@/layouts/vehicle-damage/damage-location-question/damage-location-question";
import windshieldOptions from "@/layouts/vehicle-damage/windshield-options/windshield-options";
import replaceOptionsQuestion from "@/layouts/vehicle-damage/replace-options-question/replace-options-question";

// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { storeActions } from "@/constants/store-actions";
import store from "@/store";
import baseMixin from "@/mixins/base-mixin";
import { damageLocationsParts } from "@/constants/damage-locations-parts.js";
import { damageLocationsCms } from "@/constants/damage-locations-cms.js";


export default {
  name: "vehicle-damage",
  async beforeRouteEnter(to, from, next) {
    // Call APIs
    const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);
    const damageOptionsPromise =
      baseMixin.methods.dispatchNonBlockingStoreAction(
        storeActions.GET_DAMAGE_OPTIONS,
        { carId: store.getters.vehicle.carId }
      );

    // Settle promises and get results
    const promiseResultMap = [
      {
        resultKey: "cmsContent",
        promise: cmsContentPromise,
      },
      {
        resultKey: "damageOptions",
        promise: damageOptionsPromise,
      },
    ];

    const resultMap = await settleAllPromises(promiseResultMap);

    // Call the "next" function to complete the transition to this page.
    next((vm) => {
      vm.$refs.funnelHeader.initializeComponent(
        resultMap.cmsContent.FunnelHeaderWidget
      );
      vm.$refs.vehicleBanner.initializeComponent(
        resultMap.cmsContent.VehicleBannerWidget
      );
      vm.$refs.funnelSubHeader.initializeComponent(
        resultMap.cmsContent.FunnelSubHeaderWidget
      );
      vm.$refs.damageLocation.initializeComponent(
        resultMap.cmsContent.DamageLocationQuestion, resultMap.damageOptions
      );
      vm.$refs.sideDoorOptions.initializeComponent(
        resultMap.cmsContent.SideDoorSideQuestion, resultMap.cmsContent.DriverSideReplaceOptionsQuestion, resultMap.cmsContent.PassengerSideReplaceOptionsQuestion, resultMap.damageOptions.driverSideOptions.availableReplacementOptions, resultMap.damageOptions.passengerSideOptions.availableReplacementOptions
      );
      vm.$refs.windshieldOptions.initializeComponent(
        resultMap.cmsContent.WindshieldDamageTypeQuestion, resultMap.cmsContent.WindshieldChipCountQuestion,
        resultMap.cmsContent.WindshieldReplaceOptionsQuestion, resultMap.damageOptions.windshieldOptions.availableReplacementOptions
      );
      vm.$refs.backGlassOptions.initializeComponent(
        resultMap.cmsContent.RearReplaceOptionsQuestion, resultMap.damageOptions.backGlassOptions.availableReplacementOptions
      );
      vm.$refs.funnelFooter.initializeComponent(
        resultMap.cmsContent.FunnelFooterWidget
      );
    });
  },
  data(){
    return {
      selectedDamageLocations: [],
      sideDoorOptionsData: {
        selectedDoorSides: [],
        selectedDriverSideReplaceOptions: [],
        selectedPassengerSideReplaceOptions: []
      },
      selectedWindshieldOptions: [],
      selectedRearReplaceOptions: [],
    }
  },
  methods: {
    arePagePrerequisitesValid() {
      return store.getters.vehicle.carId !== null;
  },
    resetDependentState() {
      store.dispatch(storeActions.RESET_PARTS_STATE_AND_DEPENDENCIES);
    },
    backButtonAction() {
      // route to move backwards
      this.$router.navigate(
        this.navigationScenarios.CLICKED_BACK,
        this.$route
      );
    },
    
    async forwardButtonAction() {
      const windshieldChipCount = this.selectedWindshieldOptions.selectedWindshieldChipCount && this.isWindshieldDamageLocation ? 
         this.selectedWindshieldOptions.selectedWindshieldChipCount[0] : null;

      store.commit(this.storeMutations.UPDATE_IS_REPAIR, this.isWindshieldRepair);

      if (windshieldChipCount){
        store.commit(this.storeMutations.UPDATE_NUMBER_OF_CHIPS, parseInt(windshieldChipCount));
      }

      store.commit(this.storeMutations.UPDATE_GLASS_TO_REPLACE, this.selectedGlassToReplace());
      
      const partsData = await baseMixin.methods.dispatchNonBlockingStoreAction(this.storeActions.GET_PARTS_OR_QUESTIONS,
      { carId: store.getters.vehicle.carId, glassArray: this.selectedGlassToReplace()}, false);
      
      this.navigateForward(partsData);
    },

    navigateForward(partsData){
      //found problem questions
      if (partsData.data.partsOrQuestions.some(pq => pq.partQuestions != null && pq.partQuestions.length > 0)){
        this.$router.navigateAfterSave(this.navigationScenarios.SELECTED_DAMAGE_WITH_PART_QUESTIONS, this.$route, {}, {}, partsData.data);
        return;
      }
      
      //found multiple parts for a single glass location (Windshield, Driver, Passenger, Rear)
      if (partsData.data.partsOrQuestions){
        for (var i = 0; i < partsData.data.partsOrQuestions.length; i++){
           if (partsData.data.partsOrQuestions[i].parts != null && partsData.data.partsOrQuestions[i].parts.length > 1){
            this.$router.navigateAfterSave(this.navigationScenarios.SELECTED_DAMAGE_WITH_MULTIPLE_PARTS, this.$route, {}, {}, partsData.data);
            return;
          }
        }
      }

      //if not a repair then there should only be 1 part and no problem questions at this point so save the part to the store.
      if (!this.isWindshieldRepair){
        store.commit(this.storeMutations.UPDATE_PARTS, partsData.data.partsOrQuestions[0].parts);
      }
    
      this.$router.navigateAfterSave(this.navigationScenarios.SELECTED_DAMAGE_WITH_SINGLE_PART, this.$route);
    },

    selectedGlassToReplace() {
      const selectedGlassToReplace = [];
      if (this.isWindshieldDamageLocation && !this.isWindshieldRepair){
          this.selectedWindshieldOptions.selectedWindshieldReplaceOptions.forEach(wsItem => {
            selectedGlassToReplace.push({ location: damageLocationsParts.WINDSHIELD, name: wsItem});
          })
      }

      if (this.isDriverSideReplace){
        this.sideDoorOptionsData.selectedDriverSideReplaceOptions.forEach(driverItem => {
          selectedGlassToReplace.push({ location: damageLocationsParts.DRIVER, name: driverItem});
        })
      }

      if (this.isPassengerSideReplace){
        this.sideDoorOptionsData.selectedPassengerSideReplaceOptions.forEach(passengerItem => {
          selectedGlassToReplace.push({ location: damageLocationsParts.PASSENGER, name: passengerItem});
        })
      }

      if (this.isRearWindowDamageLocation) {
          this.selectedRearReplaceOptions.forEach(rearItem => {
            selectedGlassToReplace.push({ location: damageLocationsParts.REAR, name: rearItem});
          })
      }
      
      return selectedGlassToReplace;
    },
  },
  computed:{
    isWindshieldDamageLocation() {
      return this.selectedDamageLocations.some(selectedDamages => 
        {
            return selectedDamages.toUpperCase() === damageLocationsCms.WINDSHIELD;
        });
    },
    isSideDoorDamageLocation() {
      return this.selectedDamageLocations.some(selectedDamages => 
        {
            return selectedDamages.toUpperCase() === damageLocationsCms.SIDEDOOR;
        });
    },
    isRearWindowDamageLocation() {
      return this.selectedDamageLocations.some(selectedDamages => 
        {
            return selectedDamages.toUpperCase() === damageLocationsCms.REARWINDOW;
        });
    },
    isWindshieldRepair() {
      if (!this.isWindshieldDamageLocation) return false;
      
      return this.selectedWindshieldOptions.selectedWindshieldDamageType.some(selectedDamageType => 
        {
            return selectedDamageType.toUpperCase() === "REPAIR";
        });
    },
    isDriverSideReplace() {
      if (!this.isSideDoorDamageLocation) return false;

      return this.sideDoorOptionsData.selectedDoorSides.some(selectedDriverSide => 
        {
            return selectedDriverSide.toUpperCase() === damageLocationsCms.DRIVERSIDE;
        });
    },
    isPassengerSideReplace() {
      if (!this.isSideDoorDamageLocation) return false;

      return this.sideDoorOptionsData.selectedDoorSides.some(selectedPassengerSide => 
        {
            return selectedPassengerSide.toUpperCase() === damageLocationsCms.PASSENGERSIDE;
        });
    }
  },

  components: {
    funnelHeader,
    funnelFooter,
    vehicleBanner,
    funnelSubHeader,
    sideDoorOptions,
    damageLocationQuestion,
    windshieldOptions,
    replaceOptionsQuestion,
  },
};
</script>
