#######################################################################################
# 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 datetime import timedelta
import logging
from temporalio import workflow
from temporalio.common import RetryPolicy

from osm_common.dataclasses.temporal_dataclasses import (
    VnfInstantiationState,
    VnfState,
    VnfInstantiateInput,
    VduInstantiateInput,
    ChangeNFInstantiationStateInput,
    ChangeNFStateInput,
    GetTaskQueueInput,
    PrepareVnfInput,
)

from osm_common.temporal_constants import (
    ACTIVITY_CHANGE_NF_INSTANTIATION_STATE,
    ACTIVITY_CHANGE_NF_NOTIFICATION_STATE,
    ACTIVITY_CHANGE_NF_STATE,
    ACTIVITY_GET_TASK_QUEUE,
    LCM_TASK_QUEUE,
    WORKFLOW_VDU_INSTANTIATE,
    WORKFLOW_VNF_INSTANTIATE,
    WORKFLOW_VNF_PREPARE,
)
from osm_lcm.temporal.juju_paas_activities import CharmInfoUtils

_SANDBOXED = False
retry_policy = RetryPolicy(maximum_attempts=3)
default_schedule_to_close_timeout = timedelta(minutes=10)


@workflow.defn(name=WORKFLOW_VNF_INSTANTIATE, sandboxed=_SANDBOXED)
class VnfInstantiateWorkflow:
    """Instantiate a VNF.

    Workflow Identifier:
        It is recommended that the ID for the VNF is referred as a workflow
        ID when invoking this workflow.
    """

    def __init__(self):
        self.logger = logging.getLogger(f"lcm.wfl.{self.__class__.__name__}")
        self.nf_instantiation_state = ChangeNFInstantiationStateInput(
            None, VnfInstantiationState.NOT_INSTANTIATED
        )
        self.nf_state = ChangeNFStateInput(None, VnfState.STOPPED)

    @workflow.run
    async def run(self, input: VnfInstantiateInput) -> None:
        try:
            self.nf_state.vnfr_uuid = (
                self.nf_instantiation_state.vnfr_uuid
            ) = input.vnfr_uuid

            await self.update_nf_instantiation_state()
            await self.update_nf_state()
            vnf_task_queue = await workflow.execute_activity(
                activity=ACTIVITY_GET_TASK_QUEUE,
                arg=GetTaskQueueInput(input.vnf_uuid),
                activity_id=f"{ACTIVITY_GET_TASK_QUEUE}-{input.vnf_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=default_schedule_to_close_timeout,
                retry_policy=retry_policy,
            )

            await workflow.execute_child_workflow(
                workflow=WORKFLOW_VNF_PREPARE,
                arg=PrepareVnfInput(input.vnf_uuid),
                task_queue=vnf_task_queue,
                id=f"{WORKFLOW_VNF_PREPARE}-{input.vnf_uuid}",
            )

            await self.instantiate_vdus(input.vnfr_uuid, vnf_task_queue)

            self.nf_instantiation_state.state = VnfInstantiationState.INSTANTIATED
            self.nf_state.state = VnfState.STARTED

        except Exception as e:
            workflow.logger.error(f"{WORKFLOW_VNF_INSTANTIATE} failed with {str(e)}")
            self.nf_instantiation_state.state = VnfInstantiationState.NOT_INSTANTIATED
            self.nf_state.state = VnfState.STOPPED
            raise e

        finally:
            await self.update_nf_instantiation_state()
            await self.update_nf_state()
            await self.update_nf_notification_state()

    async def update_nf_state(self):
        await workflow.execute_activity(
            activity=ACTIVITY_CHANGE_NF_STATE,
            arg=self.nf_state,
            activity_id=f"{ACTIVITY_CHANGE_NF_STATE}-{self.nf_state.vnfr_uuid}",
            task_queue=LCM_TASK_QUEUE,
            schedule_to_close_timeout=default_schedule_to_close_timeout,
            retry_policy=retry_policy,
        )

    async def update_nf_instantiation_state(self):
        await workflow.execute_activity(
            activity=ACTIVITY_CHANGE_NF_INSTANTIATION_STATE,
            arg=self.nf_instantiation_state,
            activity_id=f"{ACTIVITY_CHANGE_NF_INSTANTIATION_STATE}-{self.nf_instantiation_state.vnfr_uuid}",
            task_queue=LCM_TASK_QUEUE,
            schedule_to_close_timeout=default_schedule_to_close_timeout,
            retry_policy=retry_policy,
        )

    @staticmethod
    async def update_nf_notification_state():
        await workflow.execute_activity(
            activity=ACTIVITY_CHANGE_NF_NOTIFICATION_STATE,
            arg=None,
            activity_id=f"{ACTIVITY_CHANGE_NF_NOTIFICATION_STATE}",
            task_queue=LCM_TASK_QUEUE,
            schedule_to_close_timeout=default_schedule_to_close_timeout,
            retry_policy=retry_policy,
        )

    async def instantiate_vdus(self, vnfr_uuid, vnf_task_queue):
        # TODO: see OSMENG-989

        vnfr = {"uuid", vnfr_uuid}  # self.db.get_one("vnfrs", {"_id": vnfr_uuid})
        vnfd = {}  # self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]})
        for vdu in vnfd.get("vdu"):
            (
                vdu_instantiate_input,
                vdu_instantiate_workflow_id,
            ) = VnfInstantiateWorkflow.get_vdu_instantiate_input(vnfr, vnfd, vdu)
            await workflow.execute_child_workflow(
                workflow=WORKFLOW_VDU_INSTANTIATE,
                arg=vdu_instantiate_input,
                task_queue=vnf_task_queue,
                id=vdu_instantiate_workflow_id,
            )

    @staticmethod
    def get_vdu_instantiate_input(vnfr: dict, vnfd: dict, vdu: dict):
        model_name = vnfr.get("namespace")
        vim_id = vnfr.get("vim-account-id")
        sw_image_descs = vnfd.get("sw-image-desc")
        vdu_info = CharmInfoUtils.get_charm_info(vdu, sw_image_descs)
        vdu_instantiate_input = VduInstantiateInput(vim_id, model_name, vdu_info)
        vdu_instantiate_workflow_id = (
            vdu_instantiate_input.model_name + vdu_instantiate_input.charm_info.app_name
        )
        return vdu_instantiate_input, vdu_instantiate_workflow_id


@workflow.defn(name=WORKFLOW_VNF_PREPARE, sandboxed=_SANDBOXED)
class PrepareVnfWorkflow:
    """Prepare a VNF.

    Workflow Identifier:
        It is recommended that the ID for the VNF is referred as a workflow
        ID when invoking this workflow.
    """

    @workflow.run
    async def run(self, input: PrepareVnfInput) -> None:
        pass
