<template>
   <button class="sc-button bt-create centered mt-4" @click="openModal">
      {{ $t('add_an_address_title') }}
   </button>

   <teleport to="body">
      <modal v-if="modal.showModal"
         v-bind:modalDialogClass="modal.modalDialogClass"
         @close="modal.showModal = false">

         <template v-slot:header>
            <h3 class="modal-title">{{ $t('add_an_address_title') }}</h3>
         </template>

         <template v-slot:body>
            <div class="address_form">

               <div class="address_form__header">
                  <h4>{{ $t('select_an_address_title') }}</h4>
               </div>

               <div class="address_form__select">

                  <div class="address_form__select__body">
                     <label for="isNoAddress">
                        <input type="checkbox"
                           name="isNoAddress"
                           v-bind:placeholder="$t('isNoAddress')"
                           v-model="isNoAddress"
                           v-bind:value="value"/>
                        {{ $t('isNoAddress') }}
                     </label>

                     <country-selection
                        v-bind:address="address"
                        v-bind:getCities="getCities">
                     </country-selection>

                     <city-selection
                        v-bind:address="address"
                        v-bind:getReferenceAddresses="getReferenceAddresses">
                     </city-selection>

                     <address-selection
                        v-bind:address="address"
                        v-bind:updateMapCenter="updateMapCenter">
                     </address-selection>
                  </div>

                  <div class="address_form__select__map">
                     <address-map
                        v-bind:address="address"
                        ref="addressMap">
                     </address-map>
                  </div>
               </div>

               <div class="address_form__more">
                  <address-more
                     v-if="!isNoAddress"
                     v-bind:address="address">
                  </address-more>
               </div>
            </div>

         </template>

         <template v-slot:footer>
            <button class="sc-button green"
               @click.prevent="$emit('addNewAddress', { address, modal })">
               <i class="fa fa-plus fa-fw"></i>{{ $t('action.add')}}
            </button>
         </template>

      </modal>
   </teleport>
</template>

<script>
import Modal from './Modal';
import { fetchCountries, fetchCities, fetchReferenceAddresses } from '../_api/AddAddress'
import CountrySelection from './AddAddress/CountrySelection';
import CitySelection from './AddAddress/CitySelection';
import AddressSelection from './AddAddress/AddressSelection';
import AddressMap from './AddAddress/AddressMap';
import AddressMore from './AddAddress/AddressMore'

export default {
   name: 'AddAddresses',
   components: {
      Modal,
      CountrySelection,
      CitySelection,
      AddressSelection,
      AddressMap,
      AddressMore
   },
   props: [
   ],
   emits: ['addNewAddress'],
   data() {
      return {
         modal: {
            showModal: false,
            modalDialogClass: "modal-dialog-scrollable modal-xl"
         },
         address: {
            loaded: {
               countries: [],
               cities: [],
               addresses: [],
            },
            selected: {
               country: {},
               city: {},
               address: {},
            },
            addressMap: {
               center : [48.8589, 2.3469], // Note: LeafletJs demands [lat, lon] cfr https://macwright.com/lonlat/
               zoom: 12
            },
            isNoAddress: false,
            floor: null,
            corridor: null,
            steps: null,
            floor: null,
            flat: null,
            buildingName: null,
            extra: null,
            distribution: null,
         },
         errorMsg: {}
      }
   },
   computed: {
      isNoAddress: {
         set(value) {
            console.log('value', value);
            this.address.isNoAddress = value;
         },
         get() {
            return this.address.isNoAddress;
         }
      }
   },
   mounted() {
       this.getCountries();
   },
   methods: {
      openModal() {
         this.modal.showModal = true;
         this.resetAll();
         //this.$nextTick(function() {
         //   this.$refs.search.focus(); // positionner le curseur à l'ouverture de la modale
         //})
      },
      getCountries() {
         console.log('getCountries');
         fetchCountries().then(countries => new Promise((resolve, reject) => {
             this.address.loaded.countries = countries.results;
             resolve()
          }))
          .catch((error) => {
             this.errorMsg.push(error.message);
          });
      },
      getCities(country) {
         console.log('getCities for', country.name);
         fetchCities(country).then(cities => new Promise((resolve, reject) => {
            this.address.loaded.cities = cities.results;
            resolve()
         }))
         .catch((error) => {
            this.errorMsg.push(error.message);
         });
      },
      getReferenceAddresses(city) {
         console.log('getReferenceAddresses for', city.name);
         fetchReferenceAddresses(city).then(addresses => new Promise((resolve, reject) => {
               console.log('addresses', addresses);
               this.address.loaded.addresses = addresses.results;
               resolve();
            }))
            .catch((error) => {
               this.errorMsg.push(error.message);
            });
      },
      updateMapCenter(point) {
         console.log('point', point);
         this.address.addressMap.center[0] = point.coordinates[1];  // TODO use reverse()
         this.address.addressMap.center[1] = point.coordinates[0];
         this.$refs.addressMap.update(); // cast child methods
      },
      resetAll() {
         console.log('reset all selected');
         this.address.loaded.addresses = [];
         this.address.selected.address = {};
         this.address.loaded.cities = [];
         this.address.selected.city = {};
         this.address.selected.country = {};
         console.log('cities and addresses', this.address.loaded.cities, this.address.loaded.addresses);
      }
   }
}
</script>
