#######################################################################################
# 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
import time

from osm_common.temporal.activities.lcm import (
    NsLcmNoOp,
    UpdateNsLcmOperationState,
)


@activity.defn(name=NsLcmNoOp.__name__)
class NsLcmNoOpImpl(NsLcmNoOp):
    async def __call__(self, activity_input: NsLcmNoOp.Input) -> None:
        self.logger.debug(f"Called with: {activity_input.nslcmop}")


@activity.defn(name=UpdateNsLcmOperationState.__name__)
class UpdateNsLcmOperationStateImpl(UpdateNsLcmOperationState):
    async def __call__(self, activity_input: UpdateNsLcmOperationState.Input):
        now = time.time()

        update_lcm_operation = {
            "_admin.modified": now,
        }

        if activity_input.op_state is not None:
            update_lcm_operation["operationState"] = activity_input.op_state.name
            update_lcm_operation["statusEnteredTime"] = now

        if activity_input.stage is not None:
            update_lcm_operation["stage"] = activity_input.stage

        if activity_input.error_message is not None:
            update_lcm_operation["errorMessage"] = activity_input.error_message

        if activity_input.detailed_status is not None:
            update_lcm_operation["detailedStatus"] = activity_input.detailed_status

        self.db.set_one("nslcmops", {"_id": activity_input.op_id}, update_lcm_operation)
        self.logger.debug(
            f"Updated LCM Operation {activity_input.op_id} to {update_lcm_operation}"
        )
