<template>
  <div class="container-fluid shadow rounded-3 p-0">
    <funnelHeader :imageSrc="siteHeaderWidget.LogoImage" />
    <div class="select-car">
      <div class="select-car-form rounded text-center">
        <vehicleBanner :vehicleImageSrc="vehicleBannerWidget.GenericVehicleImage" />
        <funnelSubHeader 
          :text="pageHeaderWidgets.HeaderText"
          :hasBackButton="true"
          backButtonAccessibleText="Change Vehicle Make"
          :backButtonAction="backButtonAction"
          class="Header"
        />
        <modelQuestion v-model="selectedModel" ref="modelQuestion" />
      </div>
    </div>
  </div>
</template>

<script>
// Components
import modelQuestion from "@/layouts/vehicle-model/model-question/model-question";
import funnelHeader from "@/common-components/funnel-header/funnel-header";
import funnelSubHeader from "@/common-components/funnel-sub-header/funnel-sub-header";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
export default {
  name: "vehicle-model",
  data() {
    return {
      pageHeaderWidgets: {},
      siteHeaderWidget: {},
      vehicleBannerWidget: {},
      selectedModel: null,
    };
  },
  computed: {},

  beforeRouteEnter(to, from, next) {
    
    // Call APIs
    const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);
    const modelQuestionInitialDataPromise = modelQuestion.methods.loadInitialData();

    // Settle promises and get results
    const promiseResultMap = [
      {
        resultKey: "cmsContent",
        promise: cmsContentPromise,
      },
      {
        resultKey: "modelQuestionInitialData",
        promise: modelQuestionInitialDataPromise,
      },
    ];
    settleAllPromises(promiseResultMap).then((resultMap) => {
      // Call the "next" function to complete the transition to this page.
      next((vm) => {
        vm.pageHeaderWidgets = resultMap.cmsContent.PageHeaderWidget[0];
        vm.siteHeaderWidget = resultMap.cmsContent.SiteHeaderWidget[0];
        vm.vehicleBannerWidget = resultMap.cmsContent.VehicleBannerWidget[0];
        vm.$refs.modelQuestion.initializeComponent(resultMap.cmsContent.RadioQuestionWidget[0], resultMap.modelQuestionInitialData);
      });
    });
  },

  methods: {
    backButtonAction: function () {
      // route to move backwards
      this.$router.navigate(this.navigationScenarios.CLICKED_BACK, this.$route);
    }
  },

  watch: {
    selectedModel(model) {
      this.$store.commit(this.storeMutations.UPDATE_MODEL, model);
      this.$router.navigate(this.navigationScenarios.SELECTED_MODEL, this.$route);
    }
  },

  components: {
    modelQuestion,
    funnelHeader,
    funnelSubHeader,
    vehicleBanner,
  },
};
</script>
