import { toggleAttribute } from '../helpers/toggle-attribute';
import { showAlert } from '../helpers/show-alert';
import A11yDialog from "../../libs/a11y-dialog";

/**
 * Toggles the default placeholder item.
 * 
 * @param {HTMLElement} editor 
 */

const togglePlaceholder = (editor, total) => {
    const placeholder = editor.querySelector('.search__results-placeholder');

    if (!placeholder) return false;

    if (total <= 0) {
        placeholder.style.display = null;
        return;
    }

    placeholder.style.display = 'none';
};


/**
 * Scrolls to the corresponding information for a pin when it is clicked.
 * 
 * @param {*} editor 
 * @param {*} pin 
 */

const selectPinInfo = (editor, pinId) => {
    if (!editor || !pinId) return false;
    
    const info = editor.querySelector('[data-role=pin-tile-container]');
    const pinInfo = info.querySelector(`div[data-uid="${pinId}"]`);

    info.querySelectorAll('.search__results-item').forEach(pinInfo => {
        pinInfo.setAttribute('data-selected', false);
    })
    
    if (!pinInfo) return false;
    
    const pinInfoRect = pinInfo.getBoundingClientRect();
    const containerRect = info.getBoundingClientRect();
  
    info.scrollTo({
        top: pinInfoRect.top - containerRect.top + info.scrollTop - 12,
        behavior: 'smooth',
    });

    toggleAttribute(pinInfo, 'data-selected');

    setTimeout(() => {
        toggleAttribute(pinInfo, 'data-selected');
    }, 1000)
}


/**
 * Updates the pin total heading text.
 * 
 * @param {Number} total
 */

const updateSearchTotal = (editor, total) => {
    const text = editor.querySelector('[data-role=local-area-location-total]');

    if (!text) return false;

    text.textContent = total;
}

function pinSwitch(event)
{
    var placeid = event.target.dataset.pinid;

    var inp = document.getElementById(event.target.getAttribute('for'));
    var json = inp.value;
    try {
        var obj = JSON.parse(json);

        obj.forEach(element => {
            //console.log(element.place_id);
            if(element.place_id == placeid)
            {   //console.log(element, event.target.checked);
                element.active = event.target.checked ? 1 : 0 ;
            }
        });
        inp.value = JSON.stringify(obj);

    } catch (error) {
        //invalid json so do nothing
    }
}

function pinSearch(event)
{
    let editor = event.target.closest('[data-role="google-pin-editor"]');
    let mapcontainer = editor.querySelector('[data-role="map-container"]');
    
    let search = editor.querySelector('[data-role="search-term"]').value;

    let lat = mapcontainer.dataset.latitude;
    let lng = mapcontainer.dataset.longitude;
    
    //save the map variable into a global
    if(!('bs4data' in window))
        window.bs4data={};
    if(!('maps' in window.bs4data))
        window.bs4data.maps=[];
    if(!('maps' in window.bs4data))
        window.bs4data.markers=[];

    var location = new google.maps.LatLng( Number(lat), Number(lng));
    //infowindow = new google.maps.InfoWindow();
    var gmTarget = mapcontainer.querySelector('[data-role="google-map-container"]');
    var gmTargetId = gmTarget.getAttribute('id');
    if(gmTargetId in window.bs4data.maps)
    {
        //re-use current map
        var map = window.bs4data.maps[gmTargetId];
        for (let i = 0; i < window.bs4data.markers[gmTargetId].length; i++) {
            window.bs4data.markers[gmTargetId][i].setMap(null);
        }
        
    } else
    {
        //most often will not come here
        var map = new google.maps.Map(gmTarget, { center: location, zoom:11 });
        window.bs4data.maps[gmTargetId] = map;
    }
    window.bs4data.markers[gmTargetId]=[]; //new map reset the markers
    map.addListener("click", customPinModal); //(event.latLng); //this event prob already exists but boot and braces

    var request = {
		query: search,
		fields: ['name', 'geometry', 'rating', 'price_level', 'photos',],
		location: map.getCenter(), //location
		radius: 1
	};
	var service = new google.maps.places.PlacesService(map);

	service.textSearch(request, function (results, status) {
		console.log('111', results);

		//$('input[name=results]').val(jsonResults);
		if (status === google.maps.places.PlacesServiceStatus.OK) {

            //add each new item into the json if it is not already in there
            var inp = editor.querySelector('[data-role="pin-json"]');
            var currentpins =[];
            var json = inp.value;
            var added=0;
            if((inp=='') || (inp==null))
            { 
                currentpins = results;
                added = results.length;
            } else
            {
                try {
                    currentpins = JSON.parse(json);                    
                } catch (error) {
                    currentpins=[];
                }
                //add new pins to current
                for (var i = 0; i < results.length; i++)
                {
                    //@TODO: check if this pin exists
                    var notfound=true;

                    for (var j = 0; j < currentpins.length; j++) {
                        if( results[i].place_id==currentpins[j].place_id)
                            notfound=false;
                    }

                    if(notfound){
                        results[i].active=1;
                        currentpins.push(results[i]);
                        added++;
                    }
                    
                }
            }
            inp.value = JSON.stringify(currentpins);

            const successAlert = editor.querySelector('.alert[data-role=map-success-alert]');
            const errorAlert = editor.querySelector('.alert[data-theme=error]');

            if (added > 0) {
                showAlert(successAlert, 'map-success-alert', `${added} new location(s) added`);
            } else {
                showAlert(errorAlert, 'map-error-alert', 'No new locations added');
            }
            
            updateSearchTotal(editor, added);

            if (added > 0) {
                //and now add all these pins to the map
                togglePlaceholder(editor, currentpins.length);
                reloadTiles(editor, currentpins);
                updateSearchTotal(editor, currentpins.length);
                reloadPins(map, currentpins, gmTargetId);
            }
		}
	});



    /*
    var developmentIcon = new google.maps.Marker({
		map: map,
		position: location,
		icon: '/media/map-pin48.png'
	});
    */
   /*
	google.maps.event.addListener(developmentIcon, 'click', function () {
		//infowindow.setContent('{{ $development->development }}');
		//infowindow.open(map, this);
	});
    */
	google.maps.event.trigger(map, 'resize');
}
function removeTiles(editor)
{
    editor.querySelectorAll('[data-role="pin-tile"]:not([data-name="bs4hidden"])')
        .forEach(function(tile)
        {
            tile.remove();
        });

}
function addTile(editor, pin)
{
    var hiddenTile= editor.querySelector('[data-role="pin-tile"][data-name="bs4hidden"]');
    
    var newTile = hiddenTile.cloneNode(true);

    newTile.style.display="flex";
    pin = JSON.parse(JSON.stringify(pin)); //simplify the object;
    newTile.dataset.uid=pin.place_id;
    
    var lng = parseFloat(Number(pin.geometry.location.lng).toFixed(6));
    var lat = Math.round(1000000 * pin.geometry.location.lat)/1000000;
    newTile.dataset.longitude=lng;
    newTile.dataset.latitude=lat;

    newTile.dataset.name=pin.name;
    newTile.querySelector('input[data-action="pin-switch"]').dataset.pinid=pin.place_id;
    newTile.querySelector('div[data-role="pin-json"]').innerHTML = JSON.stringify(pin);
    newTile.querySelector('div[data-role="tile-name"]').innerHTML = pin.name;
    // newTile.querySelector('span[data-role="tile-lnglat"]').innerHTML = lng+", "+lat
    newTile.querySelector('div[data-role="tile-address"]').innerHTML = pin.formatted_address;

    newTile.querySelector('[data-action="pin-switch"]').checked = (!('active' in pin) || pin.active==1);
    
    editor.querySelector('[data-role="pin-tile-container"]')
          .append(newTile);
}


/**
 * Adds all pin tiles for a local area.
 * 
 * @param {HTMLElement} editor current local area map editor
 * @param {Array} pins array of all pins on a local are map
 */

const reloadTiles = (editor, pins) => {
    removeTiles(editor);

    pins.forEach(pin => {
        addTile(editor, pin);
    })
}

// function reloadTiles(editor, pins)
// {
//     removeTiles(editor);
//     for (var i = 0; i < pins.length; i++) {
//         addTile(editor, pins[i]);
    
//     /* @TODO: some kind of scroll to
//     google.maps.event.addListener(marker, 'click', function () {
//         infowindow.setContent(place.name);
//         infowindow.open(map, this);
//       });
//     */
//     }

// }
function reloadPins(map, pins, gmTargetId)
{
    window.bs4data.markers[gmTargetId]=[];
    for (var i = 0; i < pins.length; i++) {
        var marker = createMarker(map, pins[i], gmTargetId);
    }
}


/**
 * Controls the customer pin modal.
 * 
 * @param {Object} event 
 */

const customPinModal = (event) => {
    const target = document.elementFromPoint(event.domEvent.x, event.domEvent.y);
    const editor = target.closest('[data-role="google-pin-editor"]');
    const modal = editor.querySelector('#add-custom-pin');

    if (!modal) return false;

    const dialog = new A11yDialog(modal);
    const locationNameInput = modal.querySelector('[data-role=newpin-name]');
    const locationAddressInput = modal.querySelector('[data-role=newpin-address]');

    modal.dataset.location = JSON.stringify(event.latLng);

    dialog.show();
    
    dialog.on('hide', function (element, event) {
        dialog.destroy();

        setTimeout(() => {
            locationNameInput.value = '';
            locationAddressInput.value = '';
        }, 100);
    })
}


/**
 * Adds a custom location marker and information to a local area map
 * 
 * @param {Object} event 
 */

const addCustomPin = (event) => {
    const editor = event.target.closest('[data-role="google-pin-editor"]');
    const modal = editor.querySelector('#add-custom-pin');
    const locationNameInput = modal.querySelector('[data-role="newpin-name"]');
    const locationAddressInput = modal.querySelector('[data-role="newpin-address"]');
    const gmTarget = editor.querySelector('[data-role="google-map-container"]');
    const map = window.bs4data.maps[gmTarget.getAttribute('id')];
    const gmTargetId = gmTarget.getAttribute('id');

    const locationName = locationNameInput.value.trim();
    const locationAddress = locationAddressInput.value.trim().replace(/\s+/g, ' ');

    if (!locationName) return false;

    const newpin = {
        name: locationName,
        geometry: {
            location: JSON.parse(modal.dataset.location),
        },
        place_id: "bs4_custom_pin_" + bs4RandomID(12),
        formatted_address: locationAddress,
        active: 1,
    };

    const marker = createMarker(map, newpin, gmTargetId);

    addTile(editor, newpin);

    const inp = editor.querySelector('[data-role="pin-json"]');
    let currentpins = [];

    try {
        currentpins = JSON.parse(inp.value);
    } catch (error) {
        
    }

    currentpins.push(newpin);
    inp.value = JSON.stringify(currentpins);
    updateSearchTotal(editor, currentpins.length);
    togglePlaceholder(editor, currentpins.length);
};



function createMarker(map, place, gmTargetId) {
    //console.log('ccdev 262', place);
	var marker = new google.maps.Marker({
		map: map,
		position: place.geometry.location,
        id: place.place_id,
	});
    window.bs4data.markers[gmTargetId].push(marker);

    /// @TODO: some kind of scroll to
    google.maps.event.addListener(marker, 'click', function (event) {
        console.log('ccdev 280',marker, event);
        var target = document.elementFromPoint(event.domEvent.x, event.domEvent.y);
        var placeuid = marker.id;
        console.log('ccdev 283',marker, event);
        let editor = target.closest('[data-role="google-pin-editor"]');

        var gmTarget = editor.querySelector('[data-role="google-map-container"]');
        //var map = window.bs4data.maps[gmTarget.getAttribute('id')];
        var gmTargetId = gmTarget.getAttribute('id');
        
        var inp = editor.querySelector('[data-role="pin-json"]');
        var json = inp.value;
        try {
            var currentpins = JSON.parse(json);                    
        } catch (error) {
            var currentpins=[];
        }
        var thispin=null;
        var i = currentpins.length;
        while (i--)
        {
            if( currentpins[i].place_id==placeuid )
            {
                thispin = currentpins[i];
                i=0; //break
            }
        }
        console.log('ccdev 304', thispin)
        // popup.innerHTML = thispin.name+"<br />"+thispin.formatted_address;
		// popup.style.display = "block";
		// popup.style.opactity = 1.0;
        setTimeout(function(){
            // document.querySelector('[data-role="map-popup"]').style.display = "none";
        },5000);

        selectPinInfo(editor, placeuid);
        //if('scrollIntoView' in tile)
        //    tile.scrollIntoView();
      });

    return marker;
}
function pinTileRemove(event)
{
    var uid = event.target.closest('div[data-uid]');
    var placeuid = uid.dataset.uid;
    //now remove from the json\
    console.log('ccdev 213',event.target);
    let editor = event.target.closest('[data-role="google-pin-editor"]');
    uid.remove();

    var inp = editor.querySelector('[data-role="pin-json"]');
    var json = inp.value;
    try {
        var currentpins = JSON.parse(json);                    
    } catch (error) {
        var currentpins=[];
    }

    var i = currentpins.length;
    while (i--)
    {
        if( currentpins[i].place_id==placeuid )
        {
            console.log('ccdev 223', placeuid, currentpins[i]);
            currentpins.splice(i, 1);
            i=0; //break
        }
    }
    inp.value = JSON.stringify(currentpins);

    var gmTarget = editor.querySelector('[data-role="google-map-container"]');
    var gmTargetId = gmTarget.getAttribute('id');
    var map = window.bs4data.maps[gmTargetId];
    //removepins
    console.log('ccdev 304 markers', window.bs4data.markers[gmTargetId]);
    for (let i = 0; i < window.bs4data.markers[gmTargetId].length; i++) {
        console.log('ccdev 306', window.bs4data.markers[gmTargetId][i], placeuid);
        if(window.bs4data.markers[gmTargetId][i].id == placeuid)
        {
            window.bs4data.markers[gmTargetId][i].setMap(null);
            window.bs4data.markers[gmTargetId].splice(i, 1);
        }
    }
    updateSearchTotal(editor, currentpins.length);
    togglePlaceholder(editor, currentpins.length);
}

document.addEventListener('change', (event) => {
    bs4.log('ccdev 98', event.target);
    
    if(event.target.matches('[data-action="pin-switch"]'))
    {
        pinSwitch(event);
    } 
});
document.addEventListener('click', (event) => {
    if(event.target.matches('[data-action="google-pin-search"]'))
    {   
        pinSearch(event);
    } else if(event.target.matches('[data-action="tile-remove"]'))
    {
        pinTileRemove(event);

    } else if(event.target.matches('[data-action="maps-editor-newpin-popup-ok"]'))
    {
        addCustomPin(event);
        console.log(event.target);

    } else if(event.target.matches('[data-action="maps-editor-newpin-popup-cancel"]'))
    {
        cancelAddCustomMarker(event);

    } //else bs4.log('ccdev 515 - lick not trapped in gmaps');
});

// document.addEventListener('keyup', (event) => {
//     if (event.target.matches('[data-role=search-term]') && event.key === 'Enter') {
//         event.preventDefault();
//         pinSearch(event);
//     }
// })

// document.querySelectorAll('[data-role=google-pin-editor] [data-role=search-term]').forEach((input) => {
//     input.addEventListener('keyup', (event) => {
//         if (event.keyCode === 13) {
//             event.preventDefault();
//             console.log('Enter');
//         }
//     })
// })

document.addEventListener('keyup', (event) => {
    const form = document.querySelector('form');
    const submit = form.querySelector('button[type=submit]');


    if (event.key === 'Enter') {
        console.log(form);
        console.log(submit);
        console.log(event);
    }
})

function addClickToMaps()
{
    //wait for google maps init to have loaded
    if(!('bs4data' in window) || !('maps' in window.bs4data))
    {
        console.log('ccdev 286 no objects');
        setTimeout(addClickToMaps, 200);

    } else
    {
        console.log('ccdev addClicktomaps', ('bs4data' in window));
        document.querySelectorAll('[data-role="google-pin-editor"] [data-role="google-map-container"]').forEach(function (element)
        {
                var gmTargetId = element.getAttribute('id');
                console.log('ccdev 293', (gmTargetId in window.bs4data.maps))
                if( !(gmTargetId in window.bs4data.maps) )
                {   //initmaps has not yet been called and the map not stored in the global array
                    setTimeout(addClickToMaps, 200);

                } else
                {
                    window.bs4data.maps[gmTargetId].addListener('click', customPinModal);
                    var inp = element.closest('[data-role="google-pin-editor"]').querySelector('[data-role="pin-json"]');
                    try {
                        var currentpins = JSON.parse(inp.value);                    
                    } catch (error) {
                        var currentpins=[];
                    }
                    reloadPins(window.bs4data.maps[gmTargetId], currentpins, gmTargetId);
                }
                
        });
    }
}
document.addEventListener('DOMContentLoaded', () => {
    addClickToMaps();
});
if(!('bs4data' in window))
    window.bs4data={};
if(!('maps' in window.bs4data))
    window.bs4data.maps=[];
if(!('markers' in window.bs4data))
    window.bs4data.markers=[];
