#######################################################################################
# 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.

import asynctest
import asyncio
import unittest.mock as mock

from juju.application import Application
from juju.errors import JujuError
from juju.unit import Unit
from n2vc.temporal_libjuju import ConnectionInfo
from osm_common.dataclasses.temporal_dataclasses import CheckCharmStatusInput, ModelInfo
from osm_common.dbbase import DbException
from osm_lcm.temporal.juju_paas_activities import JujuPaasConnector
from parameterized import parameterized
from temporalio.testing import ActivityEnvironment
from unittest.mock import AsyncMock, Mock


vim_id = "some-vim-uuid"
namespace = "some-namespace"
model_info = ModelInfo(vim_id, namespace)
connection_info = ConnectionInfo(
    "1.2.3.4:17070", "user", "password", "cacert", "cloud_name", "cloud_credentials"
)


class TestJujuPaasConnector(asynctest.TestCase):
    def setUp(self):
        self.db = Mock()
        self.env = ActivityEnvironment()
        self.juju_paas_connector = JujuPaasConnector(self.db)

    @asynctest.mock.patch("osm_lcm.temporal.juju_paas_activities.Libjuju.add_model")
    @asynctest.mock.patch(
        "osm_lcm.temporal.juju_paas_activities.JujuPaasConnector._get_connection_info"
    )
    async def test_create_model_nominal_case(
        self, mock_get_connection_info, mock_add_model
    ):
        mock_get_connection_info.return_value = connection_info
        await self.env.run(self.juju_paas_connector.create_model, model_info)
        mock_get_connection_info.assert_called_once_with(vim_id)
        mock_add_model.assert_called_once_with(namespace)

    @asynctest.mock.patch("osm_lcm.temporal.juju_paas_activities.Libjuju.add_model")
    @asynctest.mock.patch(
        "osm_lcm.temporal.juju_paas_activities.JujuPaasConnector._get_connection_info"
    )
    async def test_create_model_raises_juju_exception(
        self, mock_get_connection_info, mock_add_model
    ):
        mock_get_connection_info.return_value = connection_info
        mock_add_model.side_effect = JujuError()
        with self.assertRaises(JujuError):
            await self.env.run(self.juju_paas_connector.create_model, model_info)
        mock_get_connection_info.assert_called_once_with(vim_id)
        mock_add_model.assert_called_once_with(namespace)

    @asynctest.mock.patch("osm_lcm.temporal.juju_paas_activities.Libjuju.add_model")
    @asynctest.mock.patch(
        "osm_lcm.temporal.juju_paas_activities.JujuPaasConnector._get_connection_info"
    )
    async def test_create_model_raises_db_exception(
        self, mock_get_connection_info, mock_add_model
    ):
        mock_get_connection_info.side_effect = DbException("not found")
        with self.assertRaises(DbException):
            await self.env.run(self.juju_paas_connector.create_model, model_info)
        mock_get_connection_info.assert_called_once_with(vim_id)
        mock_add_model.assert_not_called()


class JujuPaasActivitiesTest(asynctest.TestCase):
    def setUp(self) -> None:
        self.db = Mock()
        self.env = ActivityEnvironment()
        self.env.on_heartbeat = self.on_heartbeat
        self.heartbeat_count = 0
        self.heartbeat_maximum = 5

        self.controller = AsyncMock()
        self.model = Mock()
        self.controller.get_model.return_value = self.model

        async def get_controller(_: str):
            return self.controller

        self.juju_paas = JujuPaasConnector(self.db)
        self.juju_paas._get_controller = get_controller

        self.application_name = "application"
        self.application = Mock(spec=Application)
        self.application.name = self.application_name
        self.model.applications = {self.application_name: self.application}

    def on_heartbeat(self, *args, **kwargs):
        self.heartbeat_count += 1
        if self.heartbeat_count > self.heartbeat_maximum:
            self.env.cancel()

    @parameterized.expand(
        [
            ("App active, Unit active", ["active"], ["active"], 1),
            ("App blocked, Unit active", ["blocked"], ["active"], 1),
            ("App active, Unit blocked", ["active"], ["blocked"], 1),
            ("App blocked, Unit blocked", ["blocked"], ["blocked"], 1),
            (
                "App maint, then active, Unit active",
                ["maintenance", "active"],
                ["active"],
                2,
            ),
            (
                "App active, unit maint then active",
                ["active", "active"],
                ["maintenance", "active"],
                2,
            ),
        ]
    )
    async def test_check_charm_status_application_with_one_unit(
        self, _, app_events, unit_events, heartbeat_maximum
    ):
        arg = CheckCharmStatusInput(
            application_name=self.application_name,
            model_name="model",
            vim_uuid="vim-uuid",
            poll_interval=0,
        )

        self.heartbeat_maximum = heartbeat_maximum
        units = [Mock(spec=Unit)]
        self.application.units = units

        type(self.application).status = mock.PropertyMock(side_effect=app_events)

        type(units[0]).workload_status = mock.PropertyMock(side_effect=unit_events)

        await self.env.run(self.juju_paas.check_charm_status, arg)

    async def test_check_charm_status_cancel(self):
        arg = CheckCharmStatusInput(
            application_name=self.application_name,
            model_name="model",
            vim_uuid="vim-uuid",
            poll_interval=0,
        )

        self.heartbeat_maximum = 3
        units = [Mock(spec=Unit)]
        self.application.units = units

        type(self.application).status = mock.PropertyMock(
            side_effect=["maintenance", "maintenance", "maintenance", "maintenance"]
        )

        type(units[0]).workload_status = mock.PropertyMock(side_effect=[])

        with self.assertRaises(asyncio.exceptions.CancelledError):
            await self.env.run(self.juju_paas.check_charm_status, arg)

    async def test_check_charm_status_multiple_units(self):
        arg = CheckCharmStatusInput(
            application_name=self.application_name,
            model_name="model",
            vim_uuid="vim-uuid",
            poll_interval=0,
        )

        self.heartbeat_maximum = 4

        units = [Mock(spec=Unit), Mock(spec=Unit)]
        self.application.units = units

        type(self.application).status = mock.PropertyMock(
            side_effect=["active", "active", "active", "active"]
        )

        type(units[0]).workload_status = mock.PropertyMock(
            side_effect=["maintenance", "maintenance", "active", "active"]
        )

        type(units[1]).workload_status = mock.PropertyMock(
            side_effect=["maintenance", "active", "maintenance", "active"]
        )

        await self.env.run(self.juju_paas.check_charm_status, arg)
