import {
  getLocations,
  getLocationTypeByDefaultFor,
  getUserCurrentLocation,
} from "./api";

const makeConcernedPersonsLocation = (locationType, store) => {
  let locations = [];
  store.getters.suggestedEntities.forEach((e) => {
    if (e.type === "person" && e.current_household_address !== null) {
      locations.push({
        type: "location",
        id: -store.getters.suggestedEntities.indexOf(e) * 10,
        onthefly: true,
        name: e.text,
        address: {
          id: e.current_household_address.address_id,
        },
        locationType: locationType,
      });
    }
  });
  return locations;
};
const makeConcernedThirdPartiesLocation = (locationType, store) => {
  let locations = [];
  store.getters.suggestedEntities.forEach((e) => {
    if (e.type === "thirdparty" && e.address !== null) {
      locations.push({
        type: "location",
        id: -store.getters.suggestedEntities.indexOf(e) * 10,
        onthefly: true,
        name: e.text,
        address: { id: e.address.address_id },
        locationType: locationType,
      });
    }
  });
  return locations;
};
const makeAccompanyingPeriodLocation = (locationType, store) => {
  if (store.state.activity.accompanyingPeriod === null) {
    return {};
  }
  const accPeriodLocation = store.state.activity.accompanyingPeriod.location;
  return {
    type: "location",
    id: -1,
    onthefly: true,
    name: "__AccompanyingCourseLocation__",
    address: {
      id: accPeriodLocation.address_id,
      text: `${accPeriodLocation.text} - ${accPeriodLocation.postcode.code} ${accPeriodLocation.postcode.name}`,
    },
    locationType: locationType,
  };
};

export default function prepareLocations(store) {
  // find the locations
  let allLocations = getLocations().then((results) => {
    store.commit("addAvailableLocationGroup", {
      locationGroup: "Autres localisations",
      locations: results,
    });
  });

  let currentLocation = getUserCurrentLocation().then((userCurrentLocation) => {
    if (null !== userCurrentLocation) {
      store.commit("addAvailableLocationGroup", {
        locationGroup: "Ma localisation",
        locations: [userCurrentLocation],
      });
    }
  });

  let partiesLocations = [],
    partyPromise;
  ["person", "thirdparty"].forEach((kind) => {
    partyPromise = getLocationTypeByDefaultFor(kind).then(
      (kindLocationType) => {
        if (kindLocationType) {
          let concernedKindLocations;
          if (kind === "person") {
            concernedKindLocations = makeConcernedPersonsLocation(
              kindLocationType,
              store,
            );
            // add location for the parcours into suggestions
            const personLocation = makeAccompanyingPeriodLocation(
              kindLocationType,
              store,
            );
            store.commit("addAvailableLocationGroup", {
              locationGroup: "Localisation du parcours",
              locations: [personLocation],
            });
          } else {
            concernedKindLocations = makeConcernedThirdPartiesLocation(
              kindLocationType,
              store,
            );
          }

          store.commit("addAvailableLocationGroup", {
            locationGroup:
              kind === "person" ? "Usagers concernés" : "Tiers concernés",
            locations: concernedKindLocations,
          });
        }
      },
    );
    partiesLocations.push(partyPromise);
  });

  // when all location are loaded
  Promise.all([allLocations, currentLocation, ...partiesLocations]).then(() => {
    console.log("current location in activity", store.state.activity.location);
    console.log("default loation id", window.default_location_id);
    if (window.default_location_id) {
      for (let group of store.state.availableLocations) {
        let location = group.locations.find(
          (l) => l.id === window.default_location_id,
        );
        if (location !== undefined && store.state.activity.location === null) {
          store.dispatch("updateLocation", location);
          break;
        }
      }
    }
  });
}
