# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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,
        }
