<template>
    <teleport to="#location">
        <div class="mb-3 row">
            <label class="col-form-label col-sm-4">
                {{ $t("activity.location") }}
            </label>
            <div class="col-sm-8">
                <VueMultiselect
                    name="selectLocation"
                    id="selectLocation"
                    label="name"
                    track-by="id"
                    open-direction="top"
                    :multiple="false"
                    :searchable="true"
                    :placeholder="$t('activity.choose_location')"
                    :custom-label="customLabel"
                    :options="locations"
                    group-values="locations"
                    group-label="locationGroup"
                    v-model="location"
                >
                </VueMultiselect>

                <new-location v-bind:locations="locations"></new-location>
            </div>
        </div>
    </teleport>
</template>

<script>
import { mapState, mapGetters } from "vuex";
import VueMultiselect from "vue-multiselect";
import NewLocation from "./Location/NewLocation.vue";
import { getLocations, getLocationTypeByDefaultFor } from "../api.js";

export default {
    name: "Location",
    components: {
        NewLocation,
        VueMultiselect,
    },
    data() {
        return {
            locations: [],
        };
    },
    computed: {
        ...mapState(["activity"]),
        ...mapGetters(["suggestedEntities"]),
        location: {
            get() {
                return this.activity.location;
            },
            set(value) {
                this.$store.dispatch("updateLocation", value);
            },
        },
    },
    mounted() {
        getLocations().then(
            (results) => {
                getLocationTypeByDefaultFor('person').then(
                    (personLocationType) => {
                        if (personLocationType) {
                            const personLocation = this.makeAccompanyingPeriodLocation(personLocationType);
                            const concernedPersonsLocation =
                                this.makeConcernedPersonsLocation(personLocationType);
                            getLocationTypeByDefaultFor('thirdparty').then(
                                thirdpartyLocationType => {
                                    const concernedThirdPartiesLocation =
                                        this.makeConcernedThirdPartiesLocation(thirdpartyLocationType);
                                    this.locations = [
                                        {
                                            locationGroup: 'Localisation du parcours',
                                            locations: [personLocation]
                                        },
                                        {
                                            locationGroup: 'Parties concernées',
                                            locations: [...concernedPersonsLocation, ...concernedThirdPartiesLocation]
                                        },
                                        {
                                            locationGroup: 'Autres localisations',
                                            locations: results
                                        }
                                    ];
                                }
                            )
                        } else {
                            this.locations = [
                                {
                                    locationGroup: 'Localisations',
                                    locations: response.results
                                }
                            ];
                        }
                        if (window.default_location_id) {
                            let location = this.locations.filter(
                                (l) => l.id === window.default_location_id
                            );
                            this.$store.dispatch("updateLocation", location);
                        }
                    }
                )
            })
    },
    methods: {
        labelAccompanyingCourseLocation(value) {
            return `${value.address.text} (${value.locationType.title.fr})`
        },
        customLabel(value) {
            return value.locationType
                ? value.name
                    ? value.name === '__AccompanyingCourseLocation__'
                        ? this.labelAccompanyingCourseLocation(value)
                        : `${value.name} (${value.locationType.title.fr})`
                    : value.locationType.title.fr
                : '';
        },
        makeConcernedPersonsLocation(locationType) {
            let locations = [];
            this.suggestedEntities.forEach(
                (e) => {
                    if (e.type === 'person' && e.current_household_address !== null){
                        locations.push({
                            type: 'location',
                            id: -this.suggestedEntities.indexOf(e)*10,
                            onthefly: true,
                            name: e.text,
                            address: {
                                id: e.current_household_address.address_id,
                            },
                            locationType: locationType
                        });
                    }
                }
            )
            return locations;
        },
        makeConcernedThirdPartiesLocation(locationType) {
            let locations = [];
            this.suggestedEntities.forEach(
                (e) => {
                    if (e.type === 'thirdparty' && e.address !== null){
                        locations.push({
                            type: 'location',
                            id: -this.suggestedEntities.indexOf(e)*10,
                            onthefly: true,
                            name: e.text,
                            address: { id: e.address.address_id },
                            locationType: locationType
                        });
                    }
                }
            )
            return locations;
        },
        makeAccompanyingPeriodLocation(locationType) {
            const accPeriodLocation = this.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
            }
        }
    },
};
</script>
