import logging
from typing import Dict
from common.orm.fields.EnumeratedField import EnumeratedField
from common.orm.fields.FloatField import FloatField
from common.orm.fields.ForeignKeyField import ForeignKeyField
from common.orm.fields.PrimaryKeyField import PrimaryKeyField
from common.orm.fields.StringField import StringField
from common.orm.model.Model import Model
from .DeviceModel import DeviceModel
from .EndPointModel import EndPointModel
from .KpiSampleType import ORM_KpiSampleTypeEnum

LOGGER = logging.getLogger(__name__)

class KpiModel(Model):
    pk = PrimaryKeyField()
    kpi_uuid = StringField(required=True, allow_empty=False)
    kpi_description = StringField(required=False, allow_empty=True)
    kpi_sample_type = EnumeratedField(ORM_KpiSampleTypeEnum, required=True)
    device_fk = ForeignKeyField(DeviceModel)
    endpoint_fk = ForeignKeyField(EndPointModel)
    sampling_duration = FloatField(min_value=0, required=True)
    sampling_interval = FloatField(min_value=0, required=True)

    def dump_id(self) -> Dict:
        return {'kpi_id': {'uuid': self.kpi_uuid}}

    def dump_descriptor(self) -> Dict:
        result = {
            'kpi_description': self.kpi_description,
            'kpi_sample_type': self.kpi_sample_type.value,
        }
        if self.device_fk is not None:
            result['device_id'] = DeviceModel(self.database, self.device_fk).dump_id()
        if self.endpoint_fk is not None:
            result['endpoint_id'] = EndPointModel(self.database, self.endpoint_fk).dump_id()
        return result

    def dump(self) -> Dict:
        return {
            'kpi_id': self.dump_id(),
            'kpi_descriptor': self.dump_descriptor(),
            'sampling_duration_s': self.sampling_duration,
            'sampling_interval_s': self.sampling_interval,
        }
