// lookup button for component <x-bs-form-lat-long-lookup>

const init_lookup = () =>{

    document.addEventListener('click', (event) =>{
        if(event.target.matches('[data-role=bsLatLongLookupButton]'))
        {
            googleLookup(event);
        }
    });

};
const googleLookup = (event) =>{
    console.log('lookup button');

    const url = event.target.dataset.href;
    const country = event.target.dataset.country;

    let address=''
    //build the best address possible
    const elements = ['address', 'address_1', 'address1', 'address_2', 'address2', 'address_3', 'address3', 'city', 'county', 'region', 'postcode', 'zipcode', 'postalcode', 'postal_code', 'country'];
    elements.forEach( (ename) =>{
        let element = document.querySelector(`[name="${ename}"]`);
        if(element==null)
            element = document.getElementById(ename);

        if((element!=null) && (element.value!=null) && (element.value.trim()!='')){
            if(address!='')
                address += ', ';

            address += element.value.trim();

        } else if(ename=='country') {
            //no country form field so use value from button form element
            if(country=='')
                address += ', UK';
            else
                address += ', '+country;
        }
        //console.log(ename, address);

    });
    console.log('built address: '+address);

    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('ccdev 140',xhr.response);
            var location = JSON.parse(xhr.response);
            if( (location.lat==0) && (location.lng==0) )
            {
                //the default error location
                alert('An error occurred fetching the Google API,check key and account');

            } else 
            {
                let latElement = document.querySelector('[name=lat]');
                if(latElement==null)
                    latElement = document.querySelector('[name=latitude]');

                let longElement = document.querySelector('[name=long]');
                if(longElement==null)
                    longElement = document.querySelector('[name=longitude]');                

                if(latElement!=null)
                    latElement.value = Math.round(100000000 * location.lat) / 100000000;

                if(longElement!=null)
                    longElement.value = Math.round(100000000 * location.lng) / 100000000;
            }
        } else {
            console.log('xhr error status', xhr.status);
            console.log('resp', xhr.response);
            alert('An error occurred fetching the Google API, see console log, status: '+ xhr.status);
        }
    }
    var formData = new FormData();
    formData.append('address', address);

    xhr.open("POST", url, true);
    //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').content);  
    xhr.send(formData);
};
document.addEventListener("DOMContentLoaded", init_lookup);