/* eslint-disable */
var map = L.map('mapid').setView([63.8333, -152], 1),
    accessToken = 'pk.eyJ1IjoiZmx5bG9jYWwiLCJhIjoiY2t0OHUxZXB6MTVueTJ4cGVwOHRuc2s2NyJ9.YF9frLvISHfOuT7nqs3TNg',
    apiUrl = `https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=${accessToken}`;

var form = `AND(Is_Origin=1,{IsCurrent-AsOrigin}='Yes')`;

var markers = L.markerClusterGroup();
var destinationsLayer = L.layerGroup();

var points = [],
    mainOffset;

async function fetchMapData() {

    const response = await fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Airports_IATA?filterByFormula=${form}&fields[]=Airport_IATA&fields[]=Icon_Url&fields[]=Latitude_Deg&fields[]=Longitude_Deg&sort[0][field]=Airport_IATA&sort[0][direction]=asc`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Bearer keyJ2ht64ZSN57AG1'
        },
    });

    response.ok;     // => false
    response.status; // => 404

    const mapData = await response.json();

    points = mapData.records;
    mainOffset = mapData.offset;

    return mapData;
}

async function fetchMapData2(mapData) {
    if (mapData.offset) {

        const response = await fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Airports_IATA?filterByFormula=${form}&fields[]=Airport_IATA&fields[]=Icon_Url&fields[]=Latitude_Deg&fields[]=Longitude_Deg&sort[0][field]=Airport_IATA&sort[0][direction]=asc&offset=${mapData.offset}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Bearer keyJ2ht64ZSN57AG1'
            },
        });

        response.ok;     // => false
        response.status; // => 404

        const mapData2 = await response.json();

        points = [...points, ...mapData2.records];

        return mapData2;

    }
}

function getOrigIcon(icon) {

    var origIcon = L.icon({
        iconUrl: icon,
        //shadowUrl: 'leaf-shadow.png',
        iconSize: [80, 40], // size of the icon
        //shadowSize: [50, 64], // size of the shadow
        iconAnchor: [40, 40], // point of the icon which will correspond to marker's location
        //shadowAnchor: [4, 62],  // the same for the shadow
        popupAnchor: [0, 0] // point from which the popup should open relative to the iconAnchor
    });

    return origIcon;

}

function getBlueIcon() {

    var origIcon = L.icon({
        iconUrl: 'https://spencerflagg.com/flylocal/pins/pin.svg',
        //shadowUrl: 'leaf-shadow.png',
        iconSize: [14, 16], // size of the icon
        //shadowSize: [50, 64], // size of the shadow
        iconAnchor: [7, 16], // point of the icon which will correspond to marker's location
        //shadowAnchor: [4, 62],  // the same for the shadow
        popupAnchor: [0, 0] // point from which the popup should open relative to the iconAnchor
    });

    return origIcon;

}

fetchMapData().then(mapData => {
    fetchMapData2(mapData).then(function () {

        var mapDataFiltered = points.map((record) => {
            return {
                "iata": record.fields.Airport_IATA,
                "lat": record.fields.Latitude_Deg,
                "long": record.fields.Longitude_Deg,
                "icon": record.fields.Icon_Url
            }
        });

        // console.log(mapDataFiltered); // => 'Page not found'

        mapDataFiltered.forEach((record) => {

            var popupContent = `
                <div>${record.iata}</div>
                <button id='origBtn' data-iata='${record.iata}' data-lat='${record.lat}' data-long='${record.long}'>make origin</button>
            `;

            var marker = L.marker([record.lat, record.long], { icon: getOrigIcon(record.icon + '+FFFFFF+BBBBBB+000000') })
                .bindPopup(popupContent);
            //.addTo(map);

            markers.addLayer(marker);
        });
    })
});

// console.log(mapData[0].Airport_IATA);

L.tileLayer(apiUrl, {
    attribution: 'FlyLocal | Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    //id: 'mapbox/streets-v11',
    //id: 'mapbox/outdoors-v11',
    //id: 'mapbox/satellite-streets-v11',
    id: 'flylocal/ckt9x8aho0igb18mmm9ks2fsv',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: 'your.mapbox.access.token'
}).addTo(map);

map.addLayer(markers);

map.on('popupopen', function (e) {
    var thisMarker = e.popup._source;

    // console.log(thisMarker);

    var origButton = document.getElementById("origBtn"),
        destButton = document.getElementById("destBtn");

    origButton.addEventListener("click", function () {
        //alert(thisButton.dataset.iata);

        fetchDestData(origButton.dataset.iata).then(mapData => {

            var mapDataFiltered = mapData.records.map((record) => {
                return {
                    "iata": record.fields.Airport_IATA,
                    "lat": record.fields.Latitude_Deg,
                    "long": record.fields.Longitude_Deg,
                    "icon": record.fields.Icon_Url
                }
            });

            // console.log(mapDataFiltered); // => 'Page not found'

            map.removeLayer(markers);

            // re-add origin
            var marker = L.marker([thisButton.dataset.lat, thisButton.dataset.long], { icon: getBlueIcon() })
                .addTo(map);

            destinationsLayer.clearLayers();
            map.removeLayer(destinationsLayer);

            // add all destinations
            mapDataFiltered.forEach((record) => {



                var popupContent = `
                    <div>${record.iata}</div>
                    <button id='origBtn' data-iata='${record.iata}' data-lat='${record.lat}' data-long='${record.long}'>make origin</button>
                    <button id='destBtn' data-iata='${record.iata}' data-lat='${record.lat}' data-long='${record.long}'>make destination</button>
                `;

                var marker = L.marker([record.lat, record.long], { icon: getOrigIcon(record.icon + '+05FF00+04C300+000000') })
                    .bindPopup(popupContent).addTo(map);


            });

            map.addLayer(destinationsLayer);

        });

    });

    destButton.addEventListener("click", function () {

        var lat = origButton.dataset.lat,
            long = origButton.dataset.long;

        var thisArc = L.Polyline.Arc([thisButton.dataset.lat, thisButton.dataset.long], [record.lat, record.long], {
            vertices: 200,
        });

        var thisDecorator = L.polylineDecorator(thisArc, {
            patterns: [
                // defines a pattern of 10px-wide dashes, repeated every 20px on the line
                { offset: 0, repeat: 20, symbol: L.Symbol.dash({ pixelSize: 3, pathOptions: { color: '#007FFF', weight: 8, lineCap: 'square' } }) },
                { offset: '100%', repeat: 0, symbol: L.Symbol.arrowHead({ pixelSize: 15, polygon: false, pathOptions: { stroke: true, color: '#007FFF', weight: 8, lineCap: 'square' } }) }
            ]
        });

        destinationsLayer.addLayer(thisDecorator);

    });
});

async function fetchDestData(iata) {

    var destFormula = `AND(Is_Destination=1,{IsCurrent-AsDest}="Yes",(FIND("${iata}", Associated_Origin_Search)>0))`;
    const response = await fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Airports_IATA?filterByFormula=${destFormula}&fields[]=Airport_IATA&fields[]=Latitude_Deg&fields[]=Longitude_Deg&fields[]=Icon_Url&sort[0][field]=Airport_IATA&sort[0][direction]=asc`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Bearer keyJ2ht64ZSN57AG1'
        },
    });

    response.ok;     // => false
    response.status; // => 404

    const mapData = await response.json();

    points = mapData.records;
    mainOffset = mapData.offset;

    return mapData;
}
