using System; using System.Collections.Generic; using Deltares.Standard; using Deltares.Standard.Extensions; namespace Deltares.Dam.Data.Sensors { public class SensorRepository { private SensorLocation sensorLocation; private readonly HashSet names; private readonly HashSet ids; private SensorRepository() { names = new HashSet(); ids = new HashSet(); } public SensorRepository(Location location) : this() { if (location.SensorLocation == null) { location.AddNewSensorLocation(); } sensorLocation = location.SensorLocation; if (sensorLocation.Group == null) sensorLocation.Group = new Group(); } internal Group Group { get { return sensorLocation.Group; } } public IEnumerable Sensors { get { return Group.Selection; } } internal int GetUniqueSensorID() { return Group.Selection.GetUniqueID(x => x.ID); } /// /// Adds a new sensor to the location sensor group. /// /// The created Sensor public Sensor AddNew() { var factory = new SensorFactory(); Sensor sensor = factory.CreateUniqueSensor(Group.Selection); AddSensor(sensor); return sensor; } /// /// Adds the collection of sensors to the group. /// /// The sensor needs to meet the business rules before it can be added /// The sensor collection to add to the group of this location. /// /// public void Add(IEnumerable sensors) { if (sensors == null) throw new ArgumentNullException("sensors"); foreach (var sensor in sensors) Add(sensor); } /// /// Adds the specified sensor. /// /// The sensor needs to meet the business rules before it can be added /// The sensor to add. /// /// public void Add(Sensor sensor) { if (sensor == null) throw new ArgumentNullException("sensor"); if (string.IsNullOrWhiteSpace(sensor.Name)) throw new ArgumentException("Cant add this sensor because its name is empty"); if (sensor.IsTransient()) throw new ArgumentException("Cant add this sensor because its ID is not valid. The ID must be greater then -1"); if (ids.Contains(sensor.ID)) throw new ArgumentException("Cant add this sensor becuase its ID is already added"); if (names.Contains(sensor.Name)) throw new ArgumentException("Cant add this sensor because its name is already used"); AddSensor(sensor); } /// /// Adds the sensor unconditionally /// /// The sensor. private void AddSensor(Sensor sensor) { ids.Add(sensor.ID); names.Add(sensor.Name); sensorLocation.Group.Add(sensor); } /// /// Serializes the state of this repository to a XML string. /// /// internal string Serialize() { return sensorLocation.Serialize(); } /// /// Deserializes the specified XML to restore the state of this repository /// /// The XML. internal static SensorRepository Deserialize(string xml) { if (string.IsNullOrWhiteSpace(xml)) throw new ArgumentException("xml"); return new SensorRepository() { sensorLocation = SensorLocation.Deserialize(xml) }; } } }