///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////

define(['dojo/_base/declare',
  'dojo/_base/html',
  'dojo/_base/lang',
  "dojo/_base/json",
  'dojo/_base/event',
  'dojo/on',
  'dojo/Evented',
  'dojo/dom-geometry',
  'esri/tasks/PrintTask',
  'esri/tasks/PrintParameters',
  "esri/tasks/query",
  "esri/tasks/QueryTask",
  'esri/graphicsUtils',
  'jimu/utils',
  'jimu/dijit/FeatureActionPopupMenu',
  'dijit/_WidgetBase',
  'dijit/_TemplatedMixin',
  'dijit/_WidgetsInTemplateMixin',
  'dojo/text!./SelectableLayerItem.html',
  './ClearSelectionAction'
], function (declare, html, lang, JSON, Event, on, Evented, domGeom,
PrintTask, PrintParameters, Query, QueryTask, graphicsUtils, jimuUtils, PopupMenu, _WidgetBase, _TemplatedMixin,
_WidgetsInTemplateMixin, template, ClearSelectionAction) {
    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Evented], {
        baseClass: 'selectable-layer-item',
        templateString: template,

        layerName: 'layer',
        layerVisible: true,
        checked: false,
        allowExport: false,
        inited: false,
        selAcct: '',
        selOwner: '',
        selAddrNum: '',
        selAddrDir: '',
        selAddrSt: '',
        selAddrStType: '',
        selAddrCity: '',
        selAddrZip: '',
        selOwner: '',
        ptFeat: null,
        gridLayerURL: "https://montgomeryplans.org/arcgis4/rest/services/Overlays/MCAtlas_Boundaries/MapServer/1",
        wshedLayerURL: "https://montgomeryplans.org/arcgis4/rest/services/Overlays/MCAtlas_Environmental_Features/MapServer/3",

        postCreate: function () {
            this.inherited(arguments);

            this.popupMenu = PopupMenu.getInstance();
        },

        init: function (layerObject) {
            this.featureLayer = layerObject;

            var selectedCount = this.featureLayer.getSelectedFeatures().length;
            this.layerName = this.layerInfo.title || 'layer';

            this.selectedCountNode.innerHTML = selectedCount;

            if (selectedCount > 0) {
                html.removeClass(this.domNode, 'no-action');
            } else {
                html.addClass(this.domNode, 'no-action');
            }

            this.own(on(this.featureLayer, 'selection-complete', lang.hitch(this, function () {
                var selectedCount = this.featureLayer.getSelectedFeatures().length;
                var txtParcel2 = txtSize = txtWater = '';
                var txtWSSC = txtTaxMap = '';
                var selectedFeat = this.featureLayer.getSelectedFeatures();
                //                //alert("acct = " + selectedFeat[0].attributes.ACCT);
                //document.getElementById('divacctArea').innerHTML = selectedFeat[0].attributes.ACCT;
                dijit.byId("myacctHidden").set("value", selectedFeat[0].attributes.ACCT);
                this.ptFeat = selectedFeat[0].geometry.getCentroid();

                if (selectedFeat[0].attributes.DISTRICT)
                    var txtParcel = "Acct# " + selectedFeat[0].attributes.DISTRICT.trim() + "-" + selectedFeat[0].attributes.ACCT.trim() + "\n";
                else
                    var txtParcel = "Acct# " + selectedFeat[0].attributes.ACCT.trim() + "\n";

                if (selectedFeat[0].attributes.LOT) {
                    txtParcel2 = "Lot " + selectedFeat[0].attributes.LOT.trim();
                }
                if (selectedFeat[0].attributes.BLOCK) {
                    if (txtParcel2 == '')
                        txtParcel2 += "Block " + selectedFeat[0].attributes.BLOCK.trim();
                    else
                        txtParcel2 += ", Block " + selectedFeat[0].attributes.BLOCK.trim();
                }
                if (txtParcel2 != '')
                    txtParcel2 += "\n";


                if (selectedFeat[0].attributes.ACRE_OR_SQFT == "S")
                    var units = "Square Feet"
                else if (selectedFeat[0].attributes.ACRE_OR_SQFT == "A")
                    var units = "Acres"
                else
                    var units = ""

                if (selectedFeat[0].attributes.SDAT_AREA && selectedFeat[0].attributes.SDAT_AREA > 0) {
                    txtSize = "Property Size: " + Math.round(selectedFeat[0].attributes.SDAT_AREA * 100) / 100 + " " + units + "\n"
                }

                //txtWSSC = this.getGrids(this.ptFeat);
                //alert("arr = " + txtWSSC.toString());
                //txtWater = this.getWatershed(this.ptFeat);

                try {
                    txtWSSC = "WSSC Grid:\n";
                    txtTaxMap = "Tax Map:\n"
                    txtWater = "";
                    var queryTask = new QueryTask(this.gridLayerURL);
                    var query = new Query();
                    query.geometry = this.ptFeat;
                    query.outFields = ["SHEET_NUMBER", "TAXMAP"];
                    query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
                    //Execute task
                    queryTask.execute(query, function (features) {
                        if (features.features.length > 0) {
                            //alert("grid = " + features.features[0].attributes["SHEET_NUMBER"]);
                            if (features.features[0].attributes["SHEET_NUMBER"])
                                txtWSSC = "WSSC Grid: " + features.features[0].attributes["SHEET_NUMBER"] + "\n"
                            if (features.features[0].attributes["TAXMAP"])
                                txtTaxMap = "Tax Map: " + features.features[0].attributes["TAXMAP"] + "\n"
                        }
                    });
                    try {
                        var queryTask = new QueryTask(this.wshedLayerURL);
                        var query = new Query();
                        query.geometry = this.ptFeat;
                        query.outFields = ["MD12DIG_N"];
                        query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
                        //Execute task
                        queryTask.execute(query, function (features) {
                            if (features.features.length > 0) {
                                //alert("wshed try try= " + features.features[0].attributes["MD12DIG_N"]);
                                if (features.features[0].attributes["MD12DIG_N"]) {
                                    txtWater = "Watershed: " + features.features[0].attributes["MD12DIG_N"]
                                    dijit.byId("myacctArea").set("value", txtParcel + txtParcel2 + txtWSSC + txtTaxMap + txtSize + txtWater);
                                }
                            }
                        });
                    }
                    catch (error) {
                        txtWater = "";
                        dijit.byId("myacctArea").set("value", txtParcel + txtParcel2 + txtWSSC + txtTaxMap + txtSize + txtWater);
                    }
                    dijit.byId("myacctArea").set("value", txtParcel + txtParcel2 + txtWSSC + txtTaxMap + txtSize + txtWater);
                }

                catch (error) {  
                    dijit.byId("myacctArea").set("value", txtParcel + txtParcel2 + txtWSSC + txtTaxMap + txtSize + txtWater);
                }

                //                //WSSC and TaxMap Grids
                //                var queryTask = new QueryTask("https://montgomeryplans.org/arcgis4/rest/services/Overlays/MCAtlas_Boundaries/MapServer/1");
                //                var query = new Query();
                //                query.geometry = this.ptFeat;
                //                query.outFields = ["SHEET_NUMBER", "TAXMAP"];
                //                query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
                //                //Execute task
                //                queryTask.execute(query, function (features) {
                //                    if (features.features.length > 0) {
                //                        //alert("grid = " + features.features[0].attributes["SHEET_NUMBER"]);
                //                        if (features.features[0].attributes["SHEET_NUMBER"])
                //                            txtWSSC = "WSSC Grid: " + features.features[0].attributes["SHEET_NUMBER"] + "\n"
                //                        if (features.features[0].attributes["TAXMAP"])
                //                            txtTaxMap = "Tax Map: " + features.features[0].attributes["TAXMAP"] + "\n"
                //                        //myZone = features.features[0];
                //                        //myZoneAtts = myZone.attributes;
                //                        // acctText, zoneText, addrText, landuseText, overlayzoneText, cbdText, specialprotectionText, pkgText, 
                //                        //urbdistText, entzoneText, artText, taxText, bikeText, urbrenText, metText, pfaText
                //                        //for (att in myZoneAtts) {
                //                        //alert(att + " ; " + myZoneAtts[att]);
                //                        //if (serviceURL.toLowerCase().indexOf("parking") > -1 && att == "NAME")
                //                    }
                //                }, function () {
                //                    alert("error!");
                //                    txtWSSC = "WSSC Grid:\n";
                //                    txtTaxMap = "Tax Map:\n"
                //                    var queryTask = new QueryTask("https://montgomeryplans.org/arcgis4/rest/services/Overlays/MCAtlas_Environmental_Features/MapServer/3");
                //                    var query = new Query();
                //                    query.geometry = this.ptFeat;
                //                    query.outFields = ["MD12DIG_N"];
                //                    query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
                //                    //Execute task
                //                    queryTask.execute(query, function (features) {
                //                        if (features.features.length > 0) {
                //                            alert("wshed = " + features.features[0].attributes["MD12DIG_N"]);
                //                            if (features.features[0].attributes["MD12DIG_N"])
                //                                txtWater = "Watershed: " + features.features[0].attributes["MD12DIG_N"]
                //                        }
                //                    }, function () {
                //                        txtWater = "";
                //                    }).then(lang.hitch(this, function () {
                //                        dijit.byId("myacctArea").set("value", txtParcel + txtParcel2 + txtWSSC + txtTaxMap + txtSize + txtWater);
                //                        dijit.byId("myacctHidden").set("value", selectedFeat[0].attributes.ACCT);
                //                    }));
                //                }).then(lang.hitch(this, function () {
                //                    //Watersheds
                //                    var queryTask = new QueryTask("https://montgomeryplans.org/arcgis4/rest/services/Overlays/MCAtlas_Environmental_Features/MapServer/3");
                //                    var query = new Query();
                //                    query.geometry = this.ptFeat;
                //                    query.outFields = ["MD12DIG_N"];
                //                    query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
                //                    //Execute task
                //                    queryTask.execute(query, function (features) {
                //                        if (features.features.length > 0) {
                //                            //alert("grid = " + features.features[0].attributes["MD12DIG_N"]);
                //                            if (features.features[0].attributes["MD12DIG_N"])
                //                                txtWater = "Watershed: " + features.features[0].attributes["MD12DIG_N"]
                //                        }
                //                    }, function () {
                //                        txtWater = "";
                //                    }).then(lang.hitch(this, function () {
                //                        dijit.byId("myacctArea").set("value", txtParcel + txtParcel2 + txtWSSC + txtTaxMap + txtSize + txtWater);
                //                        dijit.byId("myacctHidden").set("value", selectedFeat[0].attributes.ACCT);
                //                    }));
                //                }));

                //dijit.byId("myacctArea").set("value", txtParcel + txtParcel2 + txtWSSC[0]["wssc"] + txtWSSC[0]["tax"] + txtSize + txtWater[0]);
                //dijit.byId("myacctHidden").set("value", selectedFeat[0].attributes.ACCT);


                if (selectedFeat[0].attributes.PREMISE_ADDR_HOUSENO)
                    this.selAddrNum = selectedFeat[0].attributes.PREMISE_ADDR_HOUSENO + " ";
                else
                    this.selAddrNum = "";
                if (selectedFeat[0].attributes.PREMISE_ADDR_DIRECTION)
                    this.selAddrDir = selectedFeat[0].attributes.PREMISE_ADDR_DIRECTION + " ";
                else
                    this.selAddrDir = "";
                if (selectedFeat[0].attributes.PREMISE_ADDR_STREET)
                    this.selAddrSt = selectedFeat[0].attributes.PREMISE_ADDR_STREET + " ";
                else
                    this.selAddrSt = "";
                if (selectedFeat[0].attributes.PREMISE_ADDR_STREET_TYPE)
                    this.selAddrStType = selectedFeat[0].attributes.PREMISE_ADDR_STREET_TYPE;
                if (selectedFeat[0].attributes.PREMISE_ADDR_CITY)
                    this.selAddrCity = selectedFeat[0].attributes.PREMISE_ADDR_CITY + " ";
                else
                    this.selAddrCity = "";
                if (selectedFeat[0].attributes.PREMISE_ADDR_ZIP)
                    this.selAddrZip = selectedFeat[0].attributes.PREMISE_ADDR_ZIP;
                //this.selAddrNum = selectedFeat[0].attributes.PREMISE_ADDR_HOUSENO ? selectedFeat[0].attributes.PREMISE_ADDR_HOUSENO + " " : "";
                //this.selAddrDir = selectedFeat[0].attributes.PREMISE_ADDR_DIRECTION ? selectedFeat[0].attributes.PREMISE_ADDR_DIRECTION + " " : "";
                //this.selAddrSt = selectedFeat[0].attributes.PREMISE_ADDR_STREET ? selectedFeat[0].attributes.PREMISE_ADDR_STREET + " " : "";
                //this.selAddrStType = selectedFeat[0].attributes.PREMISE_ADDR_STREET_TYPE;
                //this.selAddrCity = selectedFeat[0].attributes.PREMISE_ADDR_CITY ? selectedFeat[0].attributes.PREMISE_ADDR_CITY + " " : "";
                //this.selAddrZip = selectedFeat[0].attributes.PREMISE_ADDR_ZIP;

                var addr1 = "";
                var addr2 = "";

                if (this.selAddrNum != "" || this.selAddrDir != "" || this.selAddrSt != "" || this.selAddrStType != "")
                    addr1 = this.selAddrNum + this.selAddrDir + this.selAddrSt + this.selAddrStType + "\n";
                if (this.selAddrCity != "" || this.selAddrZip != "")
                    addr2 = this.selAddrCity + this.selAddrZip;

                if (selectedFeat[0].attributes.OWNERS_NAME)
                    this.selOwner = selectedFeat[0].attributes.OWNERS_NAME + "\n";

                dijit.byId("mylocArea").set("value", this.selOwner + addr1 + addr2);

                //var printTask = new PrintTask();
                //var params = new PrintParameters();
                //params.map = this.map;
                //var Web_Map_as_JSON = JSON.toJson(printTask._getPrintDefinition(this.map, params));
                //alert("json selLayerItem= " + Web_Map_as_JSON);

                this.selectedCountNode.innerHTML = selectedCount;
                if (selectedCount === 0) {
                    html.addClass(this.domNode, 'no-action');
                } else {
                    html.removeClass(this.domNode, 'no-action');
                }

                var selExtent = graphicsUtils.graphicsExtent(selectedFeat);
                //alert("ext = " + selExtent.xmin + " , " + selExtent.ymin + " , " + selExtent.xmax + " , " + selExtent.ymax + " , ");
                //this.map.setExtent(selExtent);

                //this.onItemSelected(selectedFeat);


            })));

            this.own(on(this.featureLayer, 'selection-clear', lang.hitch(this, function () {
                this.selectedCountNode.innerHTML = 0;
                html.addClass(this.domNode, 'no-action');
            })));

            this.layerNameNode.innerHTML = this.layerName;
            this.layerNameNode.title = this.layerName;

            if (!this.layerVisible) {
                html.addClass(this.domNode, 'invisible');
            }

            if (this.checked) {
                html.addClass(this.selectableCheckBox, 'checked');
            } else {
                html.removeClass(this.selectableCheckBox, 'checked');
            }

            this.own(on(this.selectableCheckBox, 'click', lang.hitch(this, this._toggleChecked)));
            this.own(on(this.layerContent, 'click', lang.hitch(this, this._toggleContent)));
            this.own(on(this.actionBtn, 'click', lang.hitch(this, this._showActions)));

            this.inited = true;
            this.emit('inited');
        },

        getGrids: function (pt) {
            //WSSC and TaxMap Grids
            var gridArr = [];
            var txtWSSC = "WSSC Grid:\n";
            var txtTaxMap = "Tax Map:\n";
            var queryTask = new QueryTask("https://montgomeryplans.org/arcgis4/rest/services/Overlays/MCAtlas_Boundaries/MapServer/1");
            var query = new Query();
            query.geometry = pt;
            query.outFields = ["SHEET_NUMBER", "TAXMAP"];
            query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
            //Execute task
            queryTask.execute(query, function (features) {
                if (features.features.length > 0) {
                    //alert("grid = " + features.features[0].attributes["SHEET_NUMBER"]);
                    if (features.features[0].attributes["SHEET_NUMBER"])
                        txtWSSC = "WSSC Grid: " + features.features[0].attributes["SHEET_NUMBER"] + "\n"
                    if (features.features[0].attributes["TAXMAP"])
                        txtTaxMap = "Tax Map: " + features.features[0].attributes["TAXMAP"] + "\n"
                    alert("wssc = " + txtWSSC + " , " + txtTaxMap);
                    gridArr.push({ "wssc": txtWSSC, "tax": txtTaxMap });
                }
            }, function () {
                gridArr.push({ "wssc": txtWSSC, "tax": txtTaxMap });
            });
            return gridArr;
        },

        getWatershed: function (pt) {
            //WSSC and TaxMap Grids
            var waterArr = [];
            var txtWater = "Watershed:\n";
            var queryTask = new QueryTask("https://montgomeryplans.org/arcgis4/rest/services/Overlays/MCAtlas_Environmental_Features/MapServer/3");
            var query = new Query();
            query.geometry = this.ptFeat;
            query.outFields = ["MD12DIG_N"];
            query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
            //Execute task
            queryTask.execute(query, function (features) {
                if (features.features.length > 0) {
                    //alert("grid = " + features.features[0].attributes["MD12DIG_N"]);
                    if (features.features[0].attributes["MD12DIG_N"])
                        txtWater = "Watershed: " + features.features[0].attributes["MD12DIG_N"]
                    waterArr.push({ "water": txtWater });
                }
            }, function () {
                waterArr.push({ "water": txtWater });
            });
            return waterArr;
        },

        isLayerVisible: function () {
            return this.layerVisible;
        },

        isChecked: function () {
            return this.checked;
        },

        updateLayerVisibility: function () {
            var visible = this.layerInfo.isShowInMap() && this.layerInfo.isInScale();

            if (visible !== this.layerVisible) {
                this.layerVisible = visible;

                if (this.layerVisible) {
                    html.removeClass(this.domNode, 'invisible');
                } else {
                    html.addClass(this.domNode, 'invisible');
                }
                this.emit('stateChange', {
                    visible: this.layerVisible,
                    layerInfo: this.layerInfo,
                    featureLayer: this.featureLayer
                });
            }
        },

        onItemSelected: function (selectedFeat) {
            return selectedFeat;
        },

        turnOn: function () {
            html.addClass(this.selectableCheckBox, 'checked');
            this.checked = true;
        },

        turnOff: function () {
            html.removeClass(this.selectableCheckBox, 'checked');
            this.checked = false;
        },

        toggleChecked: function () {
            this.checked = !this.checked;
            if (this.checked) {
                html.addClass(this.selectableCheckBox, 'checked');
            } else {
                html.removeClass(this.selectableCheckBox, 'checked');
            }
        },

        _toggleChecked: function (event) {
            Event.stop(event);

            html.toggleClass(this.selectableCheckBox, 'checked');
            this.checked = html.hasClass(this.selectableCheckBox, 'checked');

            this.emit('stateChange', {
                checked: this.checked,
                layerInfo: this.layerInfo
            });
        },

        _toggleContent: function (event) {
            Event.stop(event);

            if (!html.hasClass(this.domNode, 'no-action')) {
                this.emit('switchToDetails', this);
            }
        },

        _showActions: function (event) {
            Event.stop(event);

            if (html.hasClass(this.domNode, 'no-action')) {
                return;
            }
            var graphics = this.featureLayer.getSelectedFeatures();

            var selectedFeatureSet = jimuUtils.toFeatureSet(graphics);

            this.popupMenu.prepareActions(selectedFeatureSet, this.allowExport).then(lang.hitch(this, function () {
                var position = domGeom.position(event.target);
                if (graphics.length > 0) {
                    this.popupMenu.appendAction(new ClearSelectionAction({
                        folderUrl: this.folderUrl,
                        data: this.featureLayer
                    }));
                }
                this.popupMenu.show(position, this.nls.actionsTitle);
            }));
        }
    });
});