| | 1 | | using MongoDB.Driver; |
| | 2 | | using WebApi.Models; |
| | 3 | |
|
| | 4 | | namespace WebApi.DAO |
| | 5 | | { |
| | 6 | | public class SensorGoalDAO : ISensorGoalDAO |
| | 7 | | { |
| | 8 | | private readonly IMongoCollection<SensorGoal> _sensorGoalCollection; |
| | 9 | |
|
| 4 | 10 | | public SensorGoalDAO(MongoDbContext context) |
| 4 | 11 | | { |
| 4 | 12 | | _sensorGoalCollection = context.Database.GetCollection<SensorGoal>("SensorGoals"); |
| 4 | 13 | | } |
| | 14 | |
|
| | 15 | | public async Task<SensorGoal?> GetSensorGoalAsync(int hallId) |
| 4 | 16 | | { |
| | 17 | | try |
| 4 | 18 | | { |
| 4 | 19 | | return await _sensorGoalCollection.Find(g => g.HallId == hallId).FirstOrDefaultAsync(); |
| | 20 | | } |
| 0 | 21 | | catch (Exception ex) |
| 0 | 22 | | { |
| 0 | 23 | | throw new Exception($"Error retrieving sensor goal: {ex.Message}"); |
| | 24 | | } |
| 4 | 25 | | } |
| | 26 | |
|
| | 27 | | public async Task AddOrUpdateSensorGoalAsync(SensorGoal sensorGoal) |
| 5 | 28 | | { |
| | 29 | | try |
| 5 | 30 | | { |
| | 31 | | // Find the existing goal by hallId |
| 5 | 32 | | var existingGoal = await _sensorGoalCollection.Find(g => g.HallId == sensorGoal.HallId) |
| 5 | 33 | | .FirstOrDefaultAsync(); |
| | 34 | |
|
| 5 | 35 | | if (existingGoal != null) |
| 1 | 36 | | { |
| | 37 | | // Update fields while retaining the original Id |
| 1 | 38 | | existingGoal.DesiredTemperature = sensorGoal.DesiredTemperature; |
| 1 | 39 | | existingGoal.DesiredHumidity = sensorGoal.DesiredHumidity; |
| 1 | 40 | | existingGoal.DesiredCo2 = sensorGoal.DesiredCo2; |
| | 41 | |
|
| | 42 | | // Replace the existing document with the updated one |
| 1 | 43 | | await _sensorGoalCollection.ReplaceOneAsync( |
| 1 | 44 | | g => g.Id == existingGoal.Id, |
| 1 | 45 | | existingGoal, |
| 1 | 46 | | new ReplaceOptions { IsUpsert = true } |
| 1 | 47 | | ); |
| 1 | 48 | | } |
| | 49 | | else |
| 4 | 50 | | { |
| | 51 | | // Insert as new document if no existing document is found |
| 4 | 52 | | await _sensorGoalCollection.InsertOneAsync(sensorGoal); |
| 4 | 53 | | } |
| 5 | 54 | | } |
| 0 | 55 | | catch (Exception ex) |
| 0 | 56 | | { |
| 0 | 57 | | throw new Exception($"Error adding or updating sensor goal: {ex.Message}"); |
| | 58 | | } |
| | 59 | |
|
| 5 | 60 | | } |
| | 61 | |
|
| | 62 | | public async Task DeleteSensorGoalAsync(int hallId) |
| 1 | 63 | | { |
| | 64 | | try |
| 1 | 65 | | { |
| 1 | 66 | | await _sensorGoalCollection.DeleteOneAsync(g => g.HallId == hallId); |
| 1 | 67 | | } |
| 0 | 68 | | catch (Exception ex) |
| 0 | 69 | | { |
| 0 | 70 | | throw new Exception($"Error deleting sensor goal: {ex.Message}"); |
| | 71 | | } |
| | 72 | |
|
| 1 | 73 | | } |
| | 74 | | } |
| | 75 | | } |