/* Minification failed. Returning unminified contents.
(25,5-8): run-time error JS1009: Expected '}': ...
(26,8): run-time error JS1004: Expected ';'
(26,8-9): run-time error JS1195: Expected expression: :
(27,1-2): run-time error JS1002: Syntax error: }
(30,5-8): run-time error JS1009: Expected '}': ...
(31,8): run-time error JS1004: Expected ';'
(31,8-9): run-time error JS1195: Expected expression: :
(32,1-2): run-time error JS1002: Syntax error: }
(35,5-8): run-time error JS1009: Expected '}': ...
(36,8): run-time error JS1004: Expected ';'
(36,8-9): run-time error JS1195: Expected expression: :
(37,1-2): run-time error JS1002: Syntax error: }
(40,5-8): run-time error JS1009: Expected '}': ...
(41,8): run-time error JS1004: Expected ';'
(41,8-9): run-time error JS1195: Expected expression: :
(42,1-2): run-time error JS1002: Syntax error: }
(45,5-8): run-time error JS1009: Expected '}': ...
(46,8): run-time error JS1004: Expected ';'
(46,8-9): run-time error JS1195: Expected expression: :
(47,1-2): run-time error JS1002: Syntax error: }
(50,5-8): run-time error JS1009: Expected '}': ...
(51,8): run-time error JS1004: Expected ';'
(51,8-9): run-time error JS1195: Expected expression: :
(52,1-2): run-time error JS1002: Syntax error: }
 */
var aquiaBeachJs = aquiaBeachJs || {};
aquiaBeachJs.map = aquiaBeachJs.map || {};

aquiaBeachJs.map.renderMaps = function (urlStatusFetch) {
    fetch(urlStatusFetch).then(function (response) {
        return response.json();
    }).then(function (jsonStatuses) {
        renderStateMap(jsonStatuses);
        renderCountyMap(jsonStatuses);
    });
}

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollIntoView({ behavior: "smooth" });
}

const commonDotProps = {
    type: 'picture-marker', // autocasts as new PictureMarkerSymbol()
    width: '32px',
    height: '32px'
};

const flagGreen = {
    ...commonDotProps,
    url: "//static.arcgis.com/images/Symbols/Firefly/FireflyC13.png"
};

const flagYellow = {
    ...commonDotProps,
    url: "//static.arcgis.com/images/Symbols/Firefly/FireflyC17.png"
};

const flagRed = {
    ...commonDotProps,
    url: "//static.arcgis.com/images/Symbols/Firefly/FireflyC20.png"
};

const flagBlue = {
    ...commonDotProps,
    url: "//static.arcgis.com/images/Symbols/Firefly/FireflyC6.png"
};

const flagOrange = {
    ...commonDotProps,
    url: "//static.arcgis.com/images/Symbols/Firefly/FireflyB19.png"
};

const flagDefault = {
    ...commonDotProps,
    url: "//static.arcgis.com/images/Symbols/Firefly/FireflyD4.png"
};

// Add this action to the popup so it is always available in this view
const viewBeachDataAct = {
    title: "View Beach Data in Table",
    id: "show-beach-data",
    className: "esri-icon-table"
};

function createTemplate(strBeachClass) {
    return {
        title: '{name}',
        content: '<div class="text-center fs-5 pb-2"><a href="{park_url}">{parkName}</a> -- {lakeName}</div>'
            + '<div id="beachFacts" class="py-2 border-top border-bottom"><div class="row"><div class="col-6">Site ID</div><div class="col-6"><a href="{html_url}">{siteID}</a></div></div>'
            + strBeachClass
            + '<div class="lastResults"><h5>Last Sample Results</h5>'
            + '<div class="row border"><div class="col-5">Status</div><div class="col-7">{status}</div></div>'
            + '<div class="row"><div class="col-5">Sample Date</div><div class="col-7">{expression/date-with-time-zone-suffix}</div></div>'
            + '<div class="row"><div class="col-5">E. Coli</div><div class="col-7">{eColi} MPN/100ml</div></div>'
            + '<div class="row"><div class="col-5">E. Coli 5 week Geomean</div><div class="col-7">{eColi5wGeomean} MPN/100ml</div></div>'
            + '<div class="row pb-2"><div class="col-5">Microcystin</div><div class="col-7">{microcystin} ug/L</div></div>'
            + '</div>'
            + '<div class="row pt-2 border-top" style="--bs-border-opacity: .5;"><div class="col-12">{comments}</div></div>',
        actions: [viewBeachDataAct],
        fieldInfos: [{
            fieldName: "expression/date-with-time-zone-suffix",
        }],
        expressionInfos: [{
            expression: `Text(ToUTC($feature.sampleDate), "dddd, MMM D, Y, h:mm A")`,
            name: "date-with-time-zone-suffix",
        }]
    };
}

function renderStateMap(jsonStatuses) {
    require([
        "esri/views/MapView",
        "esri/Map",
        "esri/widgets/BasemapToggle",
        "esri/layers/GeoJSONLayer",
        "esri/widgets/Legend",
        "esri/core/reactiveUtils",
        "esri/widgets/Expand"
    ], (MapView, Map, BasemapToggle, GeoJSONLayer, Legend, reactiveUtils, Expand) => {
        const siteRenderer = {
            type: "unique-value",
            field: "flag",
            legendOptions: {
                title: "Current Status"
            },
            defaultSymbol: flagDefault,
            defaultLabel: "Special Status",
            uniqueValueInfos: [
                {
                    value: "Green",
                    symbol: flagGreen,
                    label: jsonStatuses["Green"] // used in the legend to describe features with this symbol
                }, {
                    value: "Yellow",
                    symbol: flagYellow,
                    label: jsonStatuses["Yellow"]
                }, {
                    value: "Red",
                    symbol: flagRed,
                    label: jsonStatuses["Red"]
                }, {
                    value: "Blue",
                    symbol: flagBlue,
                    label: jsonStatuses["Blue"]
                }]
        };

        let strBeachClass = '<div class="row"><div class="col-6">Beach Classification</div><div class="col-6">{beachClassification}</div></div></div>';

        const geojsonLayer = new GeoJSONLayer({
            url: baseApiSiteUrl + '?owner=state',
            copyright: "Iowa Department of Natural Resources",
            renderer: siteRenderer,
            popupTemplate: createTemplate(strBeachClass),
            title: 'Beach Monitoring Results'
        });

        let map = new Map({
            basemap: "topo-vector",
            layers: [geojsonLayer]
        });

        let view = new MapView({
            container: 'StateBeachMap',
            map: map,
            zoom: 8,
            center: [-93.4, 41.90], // geographic center, give or take.
            navigation: {
                browserTouchPanEnabled: false,
                momentumEnabled: false,
                rotationEnabled: false
            },
            timeZone: "America/Chicago"
        });

        // basemap toggle widget
        let toggle = new BasemapToggle({
            view: view, // view that provides access to the map's 'topo' basemap
            nextBasemap: "hybrid" // allows for toggling to the 'hybrid' basemap
        });

        // Add basemap to the top right corner of the view
        view.ui.add(toggle, "bottom-right");

        let featureLayer = map.layers.getItemAt(0);
        let legend = new Expand({
            content: new Legend({
                view: view,
                style: {
                    type: "card",
                    layout: "stack"
                },
                layerInfos: [
                    {
                        layer: featureLayer
                    }
                ]
            }),
            view: view,
            expanded: true
        });
        view.ui.add(legend, "bottom-left");
        function viewBeachData() {
            const elSearchBox = document.querySelector('#nav-state .search-input');
            elSearchBox.value = view.popup.selectedFeature.attributes.name;
            elSearchBox.focus();
            elSearchBox.blur();

            scrollToBottom('tblStateBeachResults');            
        }
        reactiveUtils.on(
            () => view.popup,
            "trigger-action",
            (event) => {
                if (event.action.id === "show-beach-data") {
                    viewBeachData();
                }
            }
        );
    });
}

function renderCountyMap(jsonStatuses) {
    require([
        "esri/views/MapView",
        "esri/Map",
        "esri/widgets/BasemapToggle",
        "esri/layers/GeoJSONLayer",
        "esri/widgets/Legend",
        "esri/core/reactiveUtils",
        "esri/widgets/Expand"
    ], (MapView, Map, BasemapToggle, GeoJSONLayer, Legend, reactiveUtils, Expand) => {

        const siteRenderer = {
            type: "unique-value",
            field: "flag",
            legendOptions: {
                title: "Current Status"
            },
            defaultSymbol: flagDefault,
            defaultLabel: "Special Status",
            uniqueValueInfos: [{
                value: "Orange",
                symbol: flagOrange,
                label: jsonStatuses["Orange"]
            }, {
                value: "Red",
                symbol: flagRed,
                label: jsonStatuses["Red"]
            }, {
                value: "Blue",
                symbol: flagBlue,
                label: jsonStatuses["Blue"]
            }]
        };

        const geojsonLayer = new GeoJSONLayer({
            url: baseApiSiteUrl + '?owner=county',
            copyright: "Iowa Department of Natural Resources",
            renderer: siteRenderer,
            popupTemplate: createTemplate(''),
            title: 'Beach Monitoring Results'
        });

        let map = new Map({
            basemap: "topo-vector",
            layers: [geojsonLayer]
        });

        let view = new MapView({
            container: 'CountyBeachMap',
            map: map,
            zoom: 8,
            center: [-93.4, 41.90], // geographic center, give or take.
            navigation: {
                browserTouchPanEnabled: false,
                momentumEnabled: false,
                rotationEnabled: false
            }
        });

        // basemap toggle widget
        let toggle = new BasemapToggle({
            view: view, // view that provides access to the map's 'topo' basemap
            nextBasemap: "hybrid" // allows for toggling to the 'hybrid' basemap
        });

        // Add basemap to the top right corner of the view
        view.ui.add(toggle, "bottom-right");

        let featureLayer = map.layers.getItemAt(0);
        let legend = new Expand({
            content: new Legend({
                view: view,
                style: {
                    type: "card",
                    layout: "stack"
                },
                layerInfos: [
                    {
                        layer: featureLayer
                    }
                ]
            }),
            view: view,
            //expanded: false
        });
        view.ui.add(legend, "bottom-left");
        function viewBeachData() {
            const elSearchBox = document.querySelector('#nav-county .search-input');
            elSearchBox.value = view.popup.selectedFeature.attributes.name;
            elSearchBox.focus();
            elSearchBox.blur();

            scrollToBottom('tblCountyBeachResults');
        }
        reactiveUtils.on(
            () => view.popup,
            "trigger-action",
            (event) => {
                if (event.action.id === "show-beach-data") {
                    viewBeachData();
                }
            }
        );
    });
};
