package dev.dinauer.metrics.service.model; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.persistence.*; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import java.time.ZonedDateTime; import java.util.Map; import java.util.UUID; @Entity @Table(name = "collection") public class Collection { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Id private String id; @Column(nullable = false) private String resource; @Column(name = "collection_name", nullable = false) private String name; @Column(nullable = false) private String timestamp; @Column(name = "unix_timestamp", nullable = false) private long unixTimestamp; @Enumerated(EnumType.STRING) @Column(name = "bucket_unit", nullable = false) private BucketUnit bucketUnit; @Column(columnDefinition = "text", nullable = false) private String metrics; @CreationTimestamp @Column(name = "created_at", updatable = false) private ZonedDateTime createdAt; @UpdateTimestamp @Column(name = "updated_at") private ZonedDateTime updatedAt; public Collection() { } public Collection(String resource, String name, String timestamp, long unixTimestamp, BucketUnit bucketUnit) { this.id = UUID.randomUUID().toString(); this.resource = resource; this.timestamp = timestamp; this.unixTimestamp = unixTimestamp; this.bucketUnit = bucketUnit; this.name = name; this.metrics = "{}"; } public String getId() { return id; } public void add(String key, double value) { Map metrics = getMetrics(); Metric metric = metrics.get(key); if (metric != null) { metric.add(value); } else { Metric newMetric = new Metric(); newMetric.add(value); metrics.put(key, newMetric); } try { this.metrics = OBJECT_MAPPER.writeValueAsString(metrics); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } private double calculateAverage(long sum, int count) { if (count == 0) { return 0; } return sum * 1.0 / count; } public String getTimestamp() { return timestamp; } public String getName() { return name; } public BucketUnit getBucketUnit() { return bucketUnit; } public String getResource() { return resource; } public Map getMetrics() { try { return OBJECT_MAPPER.readValue(metrics, new TypeReference>() {}); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } public long getUnixTimestamp() { return unixTimestamp; } public ZonedDateTime getCreatedAt() { return createdAt; } public Collection setCreatedAt(ZonedDateTime createdAt) { this.createdAt = createdAt; return this; } public ZonedDateTime getUpdatedAt() { return updatedAt; } public Collection setUpdatedAt(ZonedDateTime updatedAt) { this.updatedAt = updatedAt; return this; } }