
$("#confirmTab").on("click", function() {
    $(".venue-preview-field").each(function() {
        
        var input = $(this).find("input");
            linkedFieldId = input.attr("data-linked-field");
            linkedFieldType = input.attr("type")

        if (linkedFieldType === "check") {
            input.val($(`input[name="${linkedFieldId}"]:checked`).val());
        }
        else
            input.val($(linkedFieldId).val());

    });
})

async function viewVenueModal(venueId) {
    await openVenueModal(venueId)
    $("#venueForm input, #venueForm textarea").attr("disabled", true);
    $("#submitVenueBtn").hide();
}

async function openVenueModal(venueId) {
    // showPage($("#newVenuePages .page:first"));

    $("#detailsTab").click();
    setTimeout(() => { $("#venueName").focus() }, 300);

    $("#venueForm input, #venueForm textarea").prop("disabled", false);
    $("#submitVenueBtn").show();

    $("#venueForm").attr("data-id", venueId);

    if (venueId===-1){
        $("#venueName").val("");
        $("#venueDesc").val("");
        $(`#venueForm input[name="venueType"]`).prop("checked", false);
        $("#venueActive").prop("checked", true);
        $("#venueStreet").val("");
        $("#venueCity").val("");
        $("#venueCounty").val("");
        $("#venuePost").val("");
        $("#venueCountry").val("");
        $("#venueLat").val("");
        $("#venueLng").val("");
        $("#venuePhone").val("");
        $("#venueEmail").val("");
        $("#venueWebsite").val("");
        $("#venueFacebook").val("");
        $("#venueInstagram").val("");
        $("#venueTwitter").val("");
    }
    else {
        const venue = await getVenue(venueId);

        $("#venueName").val(venue.name);
        $("#venueDesc").val(venue.description);
        $(`#venueForm input[name="venueType"][value=${venue.venue_type}]`).prop("checked", true);
        $("#venueActive").prop("checked", venue.active);
        // $("#venueStreetNum").val(venue.name);
        $("#venueStreet").val(venue.street_address);
        $("#venueCity").val(venue.city);
        $("#venueCounty").val(venue.provence);
        $("#venuePost").val(venue.postal_code);
        $("#venueCountry").val(venue.country);
        $("#venueLat").val(venue.latitude);
        $("#venueLng").val(venue.longitude);
        $("#venuePhone").val(venue.phone_number);
        $("#venueEmail").val(venue.email_address);
        $("#venueWebsite").val(venue.website_url);
        $("#venueFacebook").val(venue.facebook_url);
        $("#venueInstagram").val(venue.instagram_url);
        $("#venueTwitter").val(venue.twitter_url);
    }

    $("#venueModal").modal("show");
}

async function deleteVenueBtn(venueId){
    await deleteVenue(venueId)
    location.reload()
}
    
$("#venueForm").on("submit", async function(e){
    e.preventDefault()
    var formData = new FormData()
    formData.append("name", $("#venueName").val())
    formData.append("description", $("#venueDesc").val())
    formData.append("venue_type", $(`#venueForm input[name="venueType"]:checked`).val())
    formData.append("active", $("#venueActive").prop("checked"))
    formData.append("street_address", $("#venueStreet").val())
    formData.append("city", $("#venueCity").val())
    formData.append("provence", $("#venueCounty").val())
    formData.append("postal_code", $("#venuePost").val())
    formData.append("country", $("#venueCountry").val())
    formData.append("latitude", $("#venueLat").val())
    formData.append("longtitude", $("#venueLng").val())
    formData.append("phone_number", $("#venuePhone").val())
    formData.append("email_address", $("#venueEmail").val())
    formData.append("website_url", $("#venueWebsite").val())
    formData.append("facebook_url", $("#venueFacebook").val())
    formData.append("instagram_url", $("#venueInstagram").val())
    formData.append("twitter_url", $("#venueTwitter").val())

    const venueId = $("#venueForm").attr("data-id")
    if (venueId==="-1"){
        await newVenue(formData)
    }
    else {
        await editVenue(venueId, formData)
    }
    // $("#venueModal").modal("hide")
    location.reload()
})

function showPage(page) {
    if (page.length === 0) return;
    $("#newVenuePages .page").removeClass("active");
    page.addClass("active");

    if (page.index() === 0) {
        $("#newVenueBack").hide();
        $("#newVenueNext").show();
        $("#newVenueFinished").hide();
    } 
    else if (page.index() + 1 === $("#newVenuePages .page").length) {
        $("#newVenueBack").show();
        $("#newVenueNext").hide();
        $("#newVenueFinished").show();
    }
    else {
        $("#newVenueBack").show();
        $("#newVenueNext").show();
        $("#newVenueFinished").hide();
    }
}

$("#newVenueNext").on("click", function() {
    const currentPage = $("#newVenuePages .page.active");
    showPage(currentPage.next(".page"));
});

$("#newVenueBack").on("click", function() {
    const currentPage = $("#newVenuePages .page.active");
    showPage(currentPage.prev(".page"));
});

let map;

async function initMap() {
    const position = { lat: 54.7023545, lng: -3.2765753 };
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

    map = new Map($("#allLocationsMap")[0], {
        zoom: 6,
        restriction: {
            latLngBounds: {
                north: 58.804,
                east: 2,
                south: 49.864,
                west: -8
            },
            strictBounds: true
        },
        center: position,
        mapId: "ALL_LOCATIONS_MAP",
        disableDefaultUI: true,
    });

    window.initAutocomplete();

    // const marker = new AdvancedMarkerElement({
    //     map: map,
    //     position: position,
    //     title: "Test"
    // });

    

    // const infoWindow = new google.maps.InfoWindow();
    // const infoWindowContent = $("#venueSearchResults")[0]
    // infoWindow.setContent(infoWindowContent);

    // autoComplete.addListener("place_changed", () => {
    //     // infoWindow.close();

    //     const place = autoComplete.getPlace();
    //     alert(JSON.stringify(place, null, 4));


    //     if (!place.geometry || !place.geometry.location) {
    //         alert("Couldn't find place");
    //         return;
    //     }

        
    // });
}

let autocomplete;

function initAutocomplete() {

    autocomplete = new google.maps.places.Autocomplete(
        $("#venueSearch")[0],
        {
            componentRestrictions: { country: "gb" },
            fields: ["address_components", "geometry"],
            types: ["address"],
            strictBounds: false
        }
    )

    autocomplete.addListener("place_changed", () => {
        const place = autocomplete.getPlace();
    
        if (!place.geometry || !place.geometry.location) {
            alert("couldn't find this place");
            return;
        }

        alert(JSON.stringify(place, null, 4));
        fillAddress(place);
    });
}

window.initAutocomplete = initAutocomplete;

function fillAddressControl(component, types, fieldSelector, component_attr="long_name") {
    if (types.some(type => component.types.includes(type))) {
        $(fieldSelector).val(component[component_attr]);
    }
}

function fillAddress(place) {

    // Clear the fields first, because sometimes we cant find data to replace them.
    $("#venueSearchResults").show();
    $("#venueSearchHelper").hide();
    $("#addressContent input[readonly], #addressContent input[readonly='readonly']").val("");

    place.address_components.forEach(component => {
        fillAddressControl(component, ["street_number"], "#venueStreetNum");
        fillAddressControl(component, ["route"], "#venueStreet");
        fillAddressControl(component, ["postal_town", "locality"], "#venueCity");
        fillAddressControl(component, ["administrative_area_level_2"], "#venueCounty");
        fillAddressControl(component, ["postal_code"], "#venuePost");
        fillAddressControl(component, ["country"], "#venueCountry");
    });

    $("#venueLat").val(place.geometry.location.lat);
    $("#venueLng").val(place.geometry.location.lng);

    // place.geometry.forEach(item => {
    //     fillAddressControl(item, ["lat"], "#venueLat", "lat");
    //     fillAddressControl(item, ["lng"], "#venueLng", "lng");        
    // });
}

$(document).ready(function() {
    initMap();
});