using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Deltares.Standard.Language;
namespace Deltares.Maps
{
///
/// Sets property values of target objects which are retrieved from the ShapeFile attributes covering a given point
///
///
public class PolygonAttributeImporter : IAttributeImporter
{
private readonly IList errors;
public PolygonAttributeImporter()
{
errors = new List();
}
public IEnumerable Errors
{
get { return errors; }
}
///
/// Gets or sets the name of the file.
///
///
/// The name of the file.
///
public string FileName { private get; set; }
public void AddError(Exception exception)
{
errors.Add(exception);
}
///
/// Sets the feature repository containing the attribute data
///
public IFeatureRepository AttributeRepository { private get; set; }
///
/// Sets the target objects containing the properties to set the retrieved coverage values on
///
public IEnumerable Targets { private get; set; }
///
/// Sets the x getter function, which is used to get the x value from a target object
///
public Func XGetter { private get; set; }
///
/// Sets the y getter function, which is used to get the y value from the target object
///
public Func YGetter { private get; set; }
///
/// Sets the list of attributes to read from the repository when a match is found
///
public IEnumerable> AttributeMappings { private get; set; }
///
/// Materializes the target object properties using its x and y values in the coverage function
///
public void Import()
{
if (Targets == null)
{
throw new InvalidOperationException("No targets set");
}
if (AttributeRepository == null)
{
throw new InvalidOperationException("No repository set");
}
if (!AttributeRepository.SupportedAttributes.Any())
{
throw new InvalidOperationException("The repository doesn't contain attributes");
}
if (AttributeMappings == null)
{
throw new InvalidOperationException("No attribute set");
}
foreach (T target in Targets)
{
double x = XGetter(target);
double y = YGetter(target);
Debug.Write(string.Format("analyzing location at ({0} {1})", x, y));
List features = AttributeRepository.GetFeaturesCovering(x, y).ToList();
if (features.Count == 0)
{
Debug.WriteLine("Error: No match");
AddError(new FeatureCoverageException(string.Format(LocalizationManager.GetTranslatedText(this, "NoMatchError"), target, FileName, x.ToString("F2"), y.ToString("F2"))));
continue;
}
if (features.Count > 1)
{
Debug.WriteLine("Error: Multiple matches");
AddError(new FeatureCoverageException(string.Format("Multiple geometries found covering point ({0} {1})", x.ToString("F2"), y.ToString("F2"))));
continue;
}
Debug.WriteLine("Success");
IFeature match = features[0];
foreach (var mapping in AttributeMappings)
{
string attributeName = mapping.Name;
if (!match.Attributes.Exists(attributeName))
{
AddError(new AttributeMissingException(attributeName));
continue;
}
mapping.Action(target, match.Attributes[attributeName]);
}
}
}
}
}