<template>
   <button v-if="!edit" class="btn btn-create mt-4" @click="openModal">
      {{ $t('add_an_address_title') }}
   </button>
   <button v-else class="btn btn-create mt-4" @click="openModal">
      {{ $t('edit_address') }}
   </button>

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

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

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

               <h4 class="h3">{{ $t('select_an_address_title') }}
                  <span v-if="loading">
                     <i class="fa fa-circle-o-notch fa-spin fa-lg"></i>
                  </span>
               </h4>

               <div class="row my-3">
                  <div class="col-lg-6">

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

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

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

                     <address-selection
                        v-if="!isNoAddress"
                        v-bind:address="address"
                        v-bind:updateMapCenter="updateMapCenter">
                     </address-selection>

                  </div>
                  <div class="col-lg-6 mt-3 mt-lg-0">

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

                  </div>
               </div>

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

            </div>
         </template>

         <template v-slot:footer>
            <button class="btn btn-create"
               @click.prevent="$emit('addNewAddress', { address, modal })">
               {{ $t('action.add')}}
            </button>
         </template>

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

<script>
import Modal from 'ChillMainAssets/vuejs/_components/Modal';
import { fetchCountries, fetchCities, fetchReferenceAddresses } from '../api'

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 {
         edit: window.mode === 'edit',
         modal: {
            showModal: false,
            modalDialogClass: "modal-dialog-scrollable modal-xl"
         },
         loading: false,
         address: {
            writeNewAddress: false,
            writeNewPostalCode: false,
            loaded: {
               countries: [],
               cities: [],
               addresses: [],
            },
            selected: {
               country: {},
               city: {},
               address: {},
            },
            newPostalCode: {
               code: null,
               name: null
            },
            addressMap: {
               center : [48.8589, 2.3469], // Note: LeafletJs demands [lat, lon] cfr https://macwright.com/lonlat/
               zoom: 12
            },
            isNoAddress: false,
            street: null,
            streetNumber: null,
            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
         //})
      },
      focusOnCity() {
          const citySelector = document.getElementById('citySelector');
          citySelector.focus();
      },
      focusOnAddress() {
          const addressSelector = document.getElementById('addressSelector');
          addressSelector.focus();
      },
      getCountries() {
         console.log('getCountries');
         this.loading = true;
         fetchCountries().then(countries => new Promise((resolve, reject) => {
             this.address.loaded.countries = countries.results;
             resolve()
             this.loading = false;
          }))
          .catch((error) => {
             this.errorMsg.push(error.message);
             this.loading = false;
          });
      },
      getCities(country) {
         console.log('getCities for', country.name);
         this.loading = true;
         fetchCities(country).then(cities => new Promise((resolve, reject) => {
            this.address.loaded.cities = cities.results.filter(c => c.origin !== 3); // filter out user-defined cities
            resolve();
            this.loading = false;
         }))
         .catch((error) => {
            this.errorMsg.push(error.message);
            this.loading = false;
         });
      },
      getReferenceAddresses(city) {
         this.loading = true;
         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();
               this.loading = false;
            }))
            .catch((error) => {
               this.errorMsg.push(error.message);
               this.loading = false;
            });
      },
      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 = {};
         this.address.isNoAddress = this.edit ? this.$store.state.editAddress.isNoAddress: false;;
         this.address.street = this.edit ? this.$store.state.editAddress.street: null;
         this.address.streetNumber = this.edit ? this.$store.state.editAddress.streetNumber: null;
         this.address.floor = this.edit ? this.$store.state.editAddress.floor: null;
         this.address.corridor = this.edit ? this.$store.state.editAddress.corridor: null;
         this.address.steps = this.edit ? this.$store.state.editAddress.steps: null;
         this.address.flat = this.edit ? this.$store.state.editAddress.flat: null;
         this.address.buildingName = this.edit ? this.$store.state.editAddress.buildingName: null;
         this.address.distribution = this.edit ? this.$store.state.editAddress.distribution: null;
         this.address.extra = this.edit ? this.$store.state.editAddress.extra: null;
         this.address.writeNewAddress = this.edit;
         this.address.writeNewPostalCode = this.edit;
         this.address.newPostalCode = this.edit ?
             {
                 code: this.$store.state.editAddress.postcode !== undefined ? this.$store.state.editAddress.postcode.code : null,
                 name: this.$store.state.editAddress.postcode !== undefined ? this.$store.state.editAddress.postcode.name : null
             } : {};
         console.log('cities and addresses', this.address.loaded.cities, this.address.loaded.addresses);
      }
   }
}
</script>

<style lang="scss">

div.address-form {
   h4.h3 {
      font-weight: bold;
   }
   div#address_map {
      height: 400px;
      width: 100%;
   }
}
</style>
