from sqlalchemy import Column, ForeignKey, Integer, String, UniqueConstraint
from sqlalchemy.orm import relationship

from rdr_server.common.enums import MetricSetType, MetricsKey
from rdr_server.model.base_model import BaseMetricsModel, ModelMixin, UTCDateTime, ModelEnum


class MetricSet(BaseMetricsModel, ModelMixin):
    """A version containing a set of metrics in the database, generated by a pipeline.

    Contains buckets with metrics grouped by HPO ID and date.
    """
    __tablename__ = 'metric_set'

    metricSetId = Column('metric_set_id', String(50), unique=True)
    metricSetType = Column('metric_set_type', ModelEnum(MetricSetType), nullable=False)
    lastModified = Column('last_modified', UTCDateTime, nullable=False)
    metrics = relationship('AggregateMetrics', cascade='all, delete-orphan', passive_deletes=True)


class AggregateMetrics(BaseMetricsModel, ModelMixin):
    """Aggregate metric value within a metric set."""
    __tablename__ = 'aggregate_metrics'

    metricSetId = Column('metric_set_id', String(50),
                         ForeignKey('metric_set.metric_set_id', ondelete='CASCADE'))
    metricsKey = Column('metrics_key', ModelEnum(MetricsKey))
    value = Column('value', String(50))
    count = Column('count', Integer, nullable=False)

    __table_args__ = (
        UniqueConstraint('metric_set_id', 'metrics_key', 'value', name='uidx_msetid_key_value'),
    )
