/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
import axios from 'axios';
import _ from 'lodash';
import resort from './resort';

export default {
  namespaced: true,
  state: {
    regions: [],
    detailedRegion: [],
    resort: {},
  },
  mutations: {
    setRegions(state, regions) {
      state.regions = regions;
    },
    clearDetailed(state) {
      state.detailedRegion = [];
    },
    addDetailed(state, detailed) {
      state.detailedRegion.push(detailed);
    },
    setResort(state, resort) {
      state.resort = resort;
    },
  },
  getters: {},
  actions: {
    getRegions({
      commit,
      dispatch,
    }) {
      commit('clearDetailed');
      axios.get(
        'https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/regions/list/ZA/',
      )
        .then((result) => {
          commit('setRegions', result.data);
          if (result.data) {
            for (const i in result.data) {
              const region = result.data[i];
              dispatch('getDetailedRegion', region);
            }
          }
        })
        .catch(console.error);
    },
    getResort({
      commit,
    }, resortCode) {
      axios.get(
        `https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/TRESORT/${
          resortCode}`,
      )
        .then((result) => {
          commit('setResort', result.data);
        })
        .catch(console.error);
    },
    getDetailedRegion({
      commit,
    }, region) {
      if (region) {
        axios
          .get(`https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/resorts/${
            region.regionCode}/`)
          .then(result => commit('addDetailed', {
            id: region.id,
            regionCode: region.regionCode,
            regionName: region.regionName,
            resorts: result.data,
          }))
          .catch(console.error);
      }
    },
  },
};
