/// <summary>
        /// Validates the meter given by object ID. Returns JSON in the following format:
        /// {
        ///		isValid: (bool),
        ///		errors: (string[])
        ///	}
        /// </summary>
        /// <param name="meterInstId"></param>
        /// <returns></returns>
        public JsonResult IsMeterValid(int objectId)
        {
            var errors = new List<string>();
            var gdalc = new GisDalc();
            var meter = gdalc.GetMeterByObjectId(objectId);
            if (meter == null) {
                errors.Add("Specified meter not found; OBJECTID: " + objectId);
            } else {
                // Begin validation.
                // 1. Inst date must be in the past.
                // inst_date should be stored in local server time zone, where this app also resides,
                // so time zones should not be an issue.
                if (!meter.inst_date.HasValue || meter.inst_date.Value > DateTime.Now) {
                    errors.Add("The installation date must be equal to the current day or before.");
                }

                if (!meter.read_date.HasValue || meter.read_date.Value > DateTime.Now) {
                    errors.Add("The initial reading date must be equal to the current day or before.");
                }

                // 20111130: Grandfathered manufacturers/models are not validated for associations.
                if (!string.IsNullOrEmpty(meter.Model) && !string.IsNullOrEmpty(meter.Manufacturer)) {
                    if (!new MeterManufacturerDalc().IsMeterAssociatedWithManufacturer(meter.Model, meter.Manufacturer)) {
                        errors.Add("The model " + HttpUtility.HtmlEncode(meter.Model) + " is not available for manufacturer " + HttpUtility.HtmlEncode(meter.Manufacturer) + ".");
                    }
                }

                Action<string, List<string>> validateSerial = (serial, errorList) => {
                    if (string.IsNullOrWhiteSpace(serial)) {
                        errorList.Add("The serial number must be entered.");
                    }
                };

                Action<string, string, List<string>> validateSize = (size, errorLabel, errorList) => {
                    if (string.IsNullOrWhiteSpace(size)) {
                        errorList.Add(string.Format("The {0} must be entered.", errorLabel));
                    }
                };

                Action<double?, List<string>> validateInitialReading = (initialReading, errorList) => {
                    if (!initialReading.HasValue) {
                        errorList.Add("The meter installation must have an initial reading.");
                    }
                };

                // 20111130: Special case "Alternate Reporting" manufacturer does not
                // require serial/size validation.
                if (!meter.Manufacturer.ToLower().StartsWith("alternate reporting")) {
                    validateSerial(meter.Serial, errors);
                    validateSize(meter.Size, "size", errors);

                    // Require at least one meter installation reading.
                    validateInitialReading(meter.InitialReading, errors);
                } else {
                    // Alternate reporting meters require special kinds of validation
                    // depending on the meter name.
                    // 20111209: This is hardcoded, because we don't expect them to change
                    // and this should only be valid/useful for about a year after deployment.
                    // If these end up changing, consider moving this to a config table in the database.
                    switch (meter.Model.ToLower()) {
                        case "alternate: electric":
                        case "alternate: natural gas":
                            // electric and nat gas validates serial and initial reading.
                            validateSerial(meter.Serial, errors);
                            validateInitialReading(meter.InitialReading, errors);
                            break;
                        case "alternate: nozzle package":
                            validateSize(meter.Size, "rate", errors);
                            validateInitialReading(meter.InitialReading, errors);
                            break;
                        case "alternate: third party":
                            // Third party validates none of this.
                            break;
                    }
                }

                // Require: (manu && model) || (gf_manu && gf_model)
                if ((string.IsNullOrWhiteSpace(meter.Manufacturer) || string.IsNullOrWhiteSpace(meter.Model))
                        && (string.IsNullOrWhiteSpace(meter.Gf_Manu) || string.IsNullOrWhiteSpace(meter.Gf_Model))) {
                    errors.Add("You must choose a Manufacturer/Model or enter a Grandfathered Manufacturer/Model.");
                }

                if (string.IsNullOrEmpty(meter.Application)) {
                    errors.Add("The meter application field cannot be blank.");
                }

            }

            return Json(new { isValid = errors.Count == 0, errors = errors }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Returns the meter whose meterInstId corresponds to the given meterId.
        /// </summary>
        /// <param name="meterInstId"></param>
        /// <returns></returns>
        public JsonResult GetMeter(int meterInstId)
        {
            var m = new GisDalc().GetMeter(meterInstId);
            if (m == null) {
                return Json(new JsonResponse(false, "The specified meter ID (" + meterInstId.ToString() + ") does not exist."));
            }

            return Json(new JsonResponse(true, m), JsonRequestBehavior.AllowGet);
        }
 /// <summary>
 /// Returns all property descriptions associated with the given contiguous acres id.
 /// </summary>
 /// <param name="CAId"></param>
 /// <returns></returns>
 public JsonResult GetAssociatedOwners(int CAObjectId)
 {
     // CAId here is actually OBJECTID.
     var caId = new GisDalc().GetContiguousAcresIdFromOBJECTID(CAObjectId);
     return Json(new JsonResponse(true, new {
         PropertyDescriptions = new PropertyDalc().GetAssociatedPropertyDescriptions(caId)
     }), JsonRequestBehavior.AllowGet);
 }
        /// <summary>
        /// Associates contiguous acres with parcel/county combo specified in form.
        /// This method deletes any existing associations, so only those parcels/counties
        /// specified here will be associated after the function returns.
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public JsonResult AssociateContiguousAcresWithParcels(FormCollection form)
        {
            try {
                int OBJECTID = form["contiguousAcresObjectId"].ToInteger();
                int contiguousAcresId = new GisDalc().GetContiguousAcresIdFromOBJECTID(OBJECTID);
                string authTicket = form["authTicket"].GetString();
                var user = GetUserFromAuthTicket(authTicket);

                if (user == null) {
                    return Json(new JsonResponse(false, "Invalid auth ticket - unable to find user."));
                }
                if (contiguousAcresId <= 0) {
                    return Json(new JsonResponse(false, "Unable to find a contiguous acres definition corresponding to OBJECTID " + OBJECTID));
                }

                string[] parcelIds = GetArrayFromFormParameter(form, "parcelIds");
                string[] counties = GetArrayFromFormParameter(form, "counties");

                if (parcelIds.Length == 0 || counties.Length == 0 || parcelIds.Length != counties.Length) {
                    return Json(new JsonResponse(false, string.Format(
                                                            "You must specify at least one parcel and county, and the length of the parcelIds and counties arrays must be the same (parcelIds.Length == {0}, counties.Length == {1})",
                                                            parcelIds.Length,
                                                            counties.Length
                                                    )));
                }

                var propDalc = new PropertyDalc();
                var parcelCounties = new List<Tuple<string, string>>();
                for (int i = 0; i < parcelIds.Length; i++) {
                    parcelCounties.Add(new Tuple<string, string>(parcelIds[i], counties[i]));
                }
                propDalc.AssociateContiguousAcres(contiguousAcresId, parcelCounties, user.Id, user.ActingAsUserId ?? user.Id);

                return Json(new JsonResponse(true));
            } catch (Exception ex) {
                return Json(new JsonResponse(false, ex.Message));
            }
        }
        public JsonResult EmailCAOwner(int caId, string message)
        {
            if (ActualUser == null) {
                return Json(new JsonResponse(false, "You are not authorized to perform that action."));
            }

            if (string.IsNullOrWhiteSpace(message)) {
                return Json(new JsonResponse(false, "You must specify a message to send."));
            }

            var ca = new GisDalc().GetContiguousAcres(caId);
            if (ca == null) {
                return Json(new JsonResponse(false, "No CA corresponding to CA ID " + caId + " was found."));
            }

            var owner = new UserDalc().GetUser(ca.OwnerClientId);
            if (owner == null) {
                return Json(new JsonResponse(false, "No owner information found for CA ID " + caId + " (owner ID " + ca.OwnerClientId + ")."));
            }

            // Prepend some boilerplate to each message explaining to the owner
            // what in the world this thing is
            message = @"This message has been sent from the High Plains Water District website on behalf of "
                        + ActingUser.DisplayName.Trim() + " (" + ActingUser.Email + @") regarding the contiguous acres described as '" + ca.Description
                        + @"', which our records indicate you own.

            To respond, you can reply directly to this email. " + ActingUser.DisplayName.Trim() + @"'s original message follows.
            --------

            " + message;

            MailHelper.Send(owner.Email, ActingUser.Email, "HPWD: Message for owner of " + ca.Description, message);
            return Json(new JsonResponse(true));
        }
        /// <summary>
        /// Creates a dynamic object representing the page state.
        /// This method will attempt to load and deserialize JSON
        /// from the database if it exists for this user (updating
        /// relevant properties appropriately), and if no existing
        /// JSON exists will construct a new object with which the
        /// user can report water usage.
        /// </summary>
        /// <returns></returns>
        protected dynamic GetPageStateJson(User user)
        {
            // Only update the _current_ reporting year or unsubmitted
            var pageStateJson = new ReportingDalc().GetReportingSummary(user.IsAdmin ? (user.ActingAsUserId ?? user.Id) : user.Id);

            ReportingSummary pageState = null;
            try {
                pageState = JsonConvert.DeserializeObject<ReportingSummary>(pageStateJson);
            } catch (Exception ex) {
                // There was a problem deserializing.
                // TODO: Notify user, possibly admins!
                throw;
            }
            if (pageState == null) {
                pageState = new ReportingSummary();
            }

            /// Returns the volume (Item1) and a bool indicating whether rollover occurred (Item2)
            /// Args: meterInstallationId, meterreadings
            Func<int, IEnumerable<JsonMeterReading>, Tuple<int, bool>> calculateVolume = (meterInstallationId, readings) => {
                double runningTotal = 0d;
                if (readings.Count() == 0) {
                    return new Tuple<int, bool>((int)runningTotal, false);
                }
                bool rolledOver = false;
                var prevReading = readings.First();
                foreach (var currentReading in readings.Skip(1)) {
                    double delta = 0;
                    if (currentReading.reading.GetValueOrDefault() < prevReading.reading.GetValueOrDefault()) {
                        // Rollover occurred
                        rolledOver = true;
                        // Retrieve the rollover value for this meter installation
                        var rollover = new MeterDalc().GetMeterInstallations(meterInstallationId).First().RolloverValue;
                        delta = (rollover - prevReading.reading.Value) + currentReading.reading.Value;
                    } else {
                        delta = currentReading.reading.GetValueOrDefault() - prevReading.reading.GetValueOrDefault();
                    }

                    runningTotal += delta * (prevReading.rate.HasValue ? prevReading.rate.Value : 1);

                    prevReading = currentReading;
                }

                return new Tuple<int, bool>((int)runningTotal, rolledOver);
            };

            // Only show Approved CAs unless the user is an admin
            var contigAcres = new GisDalc().GetContiguousAcres(user, true).Where(ca => user.IsAdmin || ca.IsApproved);

            // Key: CA ID, Value: well ids
            var wellIds = new Dictionary<int, HashSet<int>>();
            Dictionary<int, ContiguousAcres> validAcres = new Dictionary<int, ContiguousAcres>();

            // There may be load errors that got persisted from a previous page load, but we
            // only want to show current ones so clear the list.
            pageState.loadErrors.Clear();

            if (contigAcres.Count() > 0) { // Only create the service if contigAcres has stuff, because SOAP takes time
                var service = new GisServiceSoapClient();
                foreach (var ca in contigAcres) {
                    string result = "";
                    // This call is prone to failure whenever the GIS service is down.
                    try {
                        result = service.GetWellIDsByCA(ca.OBJECTID);
                    } catch (Exception ex) {
                        pageState.loadErrors.Add("Unable to load well associations for any CAs: the GIS service appears to be down!");
                    }
                    try {
                        int[] ids = JsonConvert.DeserializeObject<int[]>(result.Trim('{', '}'));
                        wellIds[ca.caID] = new HashSet<int>(ids);
                        validAcres[ca.caID] = ca;
                    } catch (JsonException ex) {
                        pageState.loadErrors.Add("Error loading CA ID " + ca.caID + ": " + ex.Message + " Service response: " + result);
                    }

                }
            }

            var mdalc = new MeterDalc();
            var rptgDalc = new ReportingDalc();

            var wellDalc = new WellDalc();
            var wells = wellDalc.GetWells(wellIds.SelectMany(x => x.Value).ToArray());
            var meterInstallations = mdalc.GetMeterInstallations(wells.SelectMany(x => x.MeterInstallationIds).ToArray()).GroupBy(x => x.Id).Select(x => x.First()).ToDictionary(x => x.Id, x => x);
            // In addition to the wells retrieved by the spatial query, we also need to
            // retrieve wells attached to the meters on that initial set.
            wells = wells.Concat(wellDalc.GetWellsByMeterInstallationIds(meterInstallations.Select(x => x.Key).ToArray()))
                            .Distinct((a,b) => a.WellId == b.WellId);

            Func<int, Dictionary<int, JsonBankedWaterRecord>> getBankedWaterTable = caId => {
                return rptgDalc.GetHistoricalBankedWater(caId).ToDictionary(x => x.year, x => x);
            };

            // func to populate a JsonCA in the current reporting year
            Func<ContiguousAcres, JsonContiguousAcres> createNewJsonCA = ca => {
                ca.Wells = wellDalc.GetWells(wellIds[ca.caID].ToArray()).ToArray();
                var reportedVolumes = mdalc.GetReportedVolumeGallons(ca.Wells.SelectMany(w => w.MeterInstallationIds), ca.caID, CurrentReportingYear);
                JsonContiguousAcres ret = new JsonContiguousAcres(ca, CurrentReportingYear);
                ReportedVolume rvol;
                ret.meterReadings = new Dictionary<int, JsonMeterReadingContainer>();
                MeterInstallation meter = null;

                foreach (var miid in ret.wells.SelectMany(x => x.meterInstallationIds).Distinct()) {
                    meterInstallations.TryGetValue(miid, out meter);
                    var container = new JsonMeterReadingContainer() {
                        meterInstallationId = miid,
                        calculatedVolumeGallons = reportedVolumes.TryGetValue(miid, out rvol) ? rvol.CalculatedVolumeGallons : 0,
                        acceptCalculation = rvol == null || !rvol.UserRevisedVolumeUnitId.HasValue,
                        userRevisedVolume = rvol != null && rvol.UserRevisedVolume.HasValue ? rvol.UserRevisedVolume.Value : 0,
                        userRevisedVolumeUnitId = rvol != null && rvol.UserRevisedVolumeUnitId.HasValue ? rvol.UserRevisedVolumeUnitId.Value : new int?(),
                        totalVolumeAcreInches = 0,
                        isNozzlePackage = meter != null ? meter.MeterType.Description().ToLower() == "nozzle package" : false,
                        isElectric = meter != null ? meter.MeterType.Description().ToLower() == "electric" : false,
                        isNaturalGas =  meter != null ? meter.MeterType.Description().ToLower() == "natural gas" : false,
                        isThirdParty = meter != null ? meter.MeterType.Description().ToLower() == "bizarro-meter" : false,
                        depthToRedbed = -99999,
                        //squeezeValue = 0,
                        unitId = meter != null ? meter.UnitId : null,
                        county = meter != null ? meter.County : "",
                        rolloverValue = meter != null ? meter.RolloverValue : 0,
                        countyId = meter != null ? meter.CountyId : -1,
                        meterType = meter != null ? meter.MeterType.Description() : "",
                        nonStandardUnits = meter != null && meter.MeterType != HPEntities.Entities.Enums.MeterType.standard ? new MeterDalc().GetUnits(meter.MeterType).Description() : "",
                        meterMultiplier = meter.Multiplier != 0 ? meter.Multiplier : 1.0d // Make sure multiplier is not 0. NULL value is already converted to 1.0d in Dalc
                    };

                    // Add depth to redbed if the meter is of 1) natural gas or 2) electric
                    if (container.isNaturalGas || container.isElectric)
                    {
                        /* //ned skip this lookup until we really need to implement it
                        var service1 = new GisServiceSoapClient();
                        string depthInString = service1.GetDepthToRedbedByMeter(miid);
                        string depthInString = "Implement this later"
                        double depth = -99999;

                        if (!Double.TryParse(depthInString, out depth))
                            depth = -99999;
                        */
                        double depth = 100;  //take this out when the above works
                        container.depthToRedbed = depth;
                    }

                    container.readings = (from mr in mdalc.GetReadings(miid, CurrentReportingYear).Reverse() // By default, they're ordered by reading date desc
                                          select new JsonMeterReading() {
                                              reading = mr.Reading,
                                              rate = mr.Rate,
                                              isValidBeginReading = ReportingDalc.IsMeterReadingValidBeginReading(mr, CurrentReportingYear),
                                              isValidEndReading = ReportingDalc.IsMeterReadingValidEndReading(mr, CurrentReportingYear),
                                              isAnnualTotalReading = ReportingDalc.IsMeterReadingAnnualTotal(mr, CurrentReportingYear),
                                              meterInstalltionReadingID = mr.MeterInstallationReadingId
                                          }).ToArray();
                    ret.meterReadings[miid] = container;
                }

                ret.meterInstallationErrors = GetMeterInstallationErrors(ca, wellIds[ca.caID]);

                ret.bankedWaterHistory = getBankedWaterTable(ca.caID);
                JsonBankedWaterRecord bankedWaterLastYear;
                ret.annualUsageSummary = new JsonAnnualUsageSummary() {
                    contiguousArea = ca.AreaInAcres,
                    annualVolume = 0, // this will only be populated after submittal
                    allowableApplicationRate = rptgDalc.GetAllowableProductionRate(CurrentReportingYear),
                    bankedWaterFromPreviousYear = ret.bankedWaterHistory.TryGetValue(CurrentReportingYear - 1, out bankedWaterLastYear) ? bankedWaterLastYear.bankedInches : 0
                };

                ret.isSubmitted = rptgDalc.IsSubmitted(ca.caID, CurrentReportingYear);
                ret.ownerClientId = ca.OwnerClientId;
                ret.isCurrentUserOwner = (this.ActualUser.ActingAsUserId ?? this.ActualUser.Id) == ca.OwnerClientId;
                return ret;
            };

            JsonReportingYear year;
            if (pageState.years.TryGetValue(CurrentReportingYear, out year)) {
                // Check the existing year object and update as necessary
                // For now, wholly reload any CAs that have not yet been submitted.

                List<JsonContiguousAcres> removals = year.contiguousAcres.Where(ca => !ca.isSubmitted).ToList();
                HashSet<int> submittedCaIds = new HashSet<int>(year.contiguousAcres.Where(ca => ca.isSubmitted).Select(x => x.number));

                // Ensure that all the CAs are still applicable to this account - the CA IDs need
                // to match what's presently associated with the user account, else they're removed.
                foreach (var ca in removals) {
                    year.contiguousAcres.Remove(ca);
                }

                // Add any CAs that were missing from the original state
                foreach (var kv in validAcres) {
                    if (!submittedCaIds.Contains(kv.Value.caID)) {
                        year.contiguousAcres.Add(createNewJsonCA(kv.Value));
                    }
                    for (int i = 0; i < year.contiguousAcres.Count; i++) {
                        if (year.contiguousAcres[i].number == kv.Value.caID) {
                            year.contiguousAcres[i].meterInstallationErrors = GetMeterInstallationErrors(kv.Value, wellIds[kv.Value.caID]);
                            year.contiguousAcres[i].wells = kv.Value.Wells.Select(w => new JsonWell(w)).ToArray();
                        }
                    }
                    //year.contiguousAcres.Where(jca => jca.number == kv.Value.caID).First().meterInstallationErrors = GetMeterInstallationErrors(kv.Value, wellIds[kv.Value.caID]);
                }

                foreach (var ca in year.contiguousAcres) {
                    // This is used on the frontend to decide whether to show the user an editable form.
                    // Only CA owners get the editable form.
                    ca.isCurrentUserOwner = (this.ActualUser.ActingAsUserId ?? this.ActualUser.Id) == ca.ownerClientId;

                }

            } else { // No existing year record exists; create a new one
                year = new JsonReportingYear();
                year.contiguousAcres = validAcres.Values.Select(ca => {
                    return createNewJsonCA(ca);
                }).ToList();

                pageState.years[CurrentReportingYear] = year;

            }

            // Populate meterInstallations by retrieving metadata for all used meter installations
            HashSet<int> meterInstallationIds = new HashSet<int>((from y in pageState.years
                                                                  from ca in y.Value.contiguousAcres
                                                                  from w in ca.wells
                                                                  select w.meterInstallationIds).SelectMany(x => x));

            // Converting this directly to a dictionary will fail in the event that a meter
            // is associated with wells in multiple counties. However, that case doesn't really
            // make any sense and would break all sorts of other things (such as meter unit conversion factors
            // that are specific to counties), so we're going to assume that there's always
            // a single county.
            pageState.meterInstallations = mdalc.GetMeterInstallations(meterInstallationIds.ToArray())
                                                .GroupBy(x => x.Id)
                                                .Select(mi => new JsonMeterInstallation(mi.First()))
                                                .ToDictionary(
                                                    x => x.id,
                                                    x => x
                                                );

            pageState.currentReportingYear = CurrentReportingYear;

            pageState.isReportingAllowed = IsReportingAllowed;
            pageState.adminOverride = ((!IsReportingAllowed) && this.ActualUser.IsAdmin);

            pageState.cafoLookups = rptgDalc.GetCafoLookups();

            // Go through and check all the submittal states of the CAs
            foreach (var ca in pageState.years[CurrentReportingYear].contiguousAcres) {
                ca.isSubmitted = rptgDalc.IsSubmitted(ca.number, CurrentReportingYear);
                if (ca.isSubmitted) {
                    // If it was a submitted CA, the banked water history table
                    // still needs to be loaded because it wasn't set above.
                    ca.bankedWaterHistory = getBankedWaterTable(ca.number);
                }

            }

            return pageState;
        }