#######################################################################################
# Copyright ETSI Contributors and Others.
#
# 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.

from temporalio import activity
from time import time

from osm_common.temporal.activities.ns import (
    GetNsRecord,
    GetVnfDetails,
    UpdateNsState,
)


@activity.defn(name=GetVnfDetails.__name__)
class GetVnfDetailsImpl(GetVnfDetails):
    async def __call__(
        self, activity_input: GetVnfDetails.Input
    ) -> GetVnfDetails.Output:
        vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": activity_input.ns_uuid})
        return GetVnfDetails.Output(
            vnf_details=[(vnfr["id"], vnfr["member-vnf-index-ref"]) for vnfr in vnfrs]
        )


@activity.defn(name=GetNsRecord.__name__)
class GetNsRecordImpl(GetNsRecord):
    async def __call__(self, activity_input: GetNsRecord.Input) -> GetNsRecord.Output:
        nsr = self.db.get_one("nsrs", {"_id": activity_input.nsr_uuid})
        self.logger.debug("Got the nsr from Database for VNF operations.")
        return GetNsRecord.Output(nsr=nsr)


@activity.defn(name=UpdateNsState.__name__)
class UpdateNsStateImpl(UpdateNsState):
    async def __call__(self, activity_input: UpdateNsState.Input) -> None:
        update_ns_state = {
            "nsState": activity_input.state.name,
            # "errorDescription" : data.message,
            "_admin.nsState": activity_input.state.name,
            "_admin.detailed-status": activity_input.message,
            "_admin.modified": time(),
        }
        self.db.set_one("nsrs", {"_id": activity_input.ns_uuid}, update_ns_state)
        self.logger.debug(
            f"Updated NS {activity_input.ns_uuid} to {activity_input.state.name}"
        )
