<template>
  <div class="page-container-grouped-styles">
    <funnelHeader cmsWidgetName="FunnelHeaderWidget" />
    <div class="select-car">
      <div class="select-car-form rounded text-center">
        <vehicleBanner cmsWidgetName="VehicleBannerWidget" displayGenericVehicleImage />
        <funnelSubHeader
            cmsWidgetName="FunnelSubHeaderWidget"
            :hasBackButton="true"
            @click-event="backButtonAction"
        />
        <div class="fade-on-route-transition">
          <makeQuestion v-model="selectedMake" ref="makeQuestion" cmsWidgetName="VehicleMakeQuestion" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// Components
import makeQuestion from "@/layouts/vehicle-make/make-question/make-question";
import funnelHeader from "@/common-components/funnel-header/funnel-header";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
import funnelSubHeader from "@/common-components/funnel-sub-header/funnel-sub-header";
// Supporting files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import { storeMutations } from "@/constants/store-mutations";
import { storeActions } from "@/constants/store-actions";
import store from "@/store";

export default {
  name: "vehicle-make",
  data() {
    return {
      selectedMake: null,
    };
  },
  computed: {},

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

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

    const resultMap = await settleAllPromises(promiseResultMap);
    // Call the "next" function to complete the transition to this page.
    next((vm) => {
      vm.setCmsContent(resultMap.cmsContent);
      vm.$refs.makeQuestion.initializeComponent(
        resultMap.makeQuestionInitialData
      );
    });
  },

  methods: {
    backButtonAction() {
      // route to move backwards
      this.$router.navigate(
        this.navigationScenarios.CLICKED_BACK,
        this.$route
      );
    },
    arePagePrerequisitesValid() {
      if (store.getters.vehicle.year){
        return true;
      }
      return false;
    },
  },

  watch: {
    selectedMake(make) {
      this.dispatchStoreAction(storeActions.SAVE_VEHICLE_MAKE, make, false); 
      this.$router.navigate(
        this.navigationScenarios.SELECTED_MAKE,
        this.$route
      );
    },
  },

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