#!/usr/bin/env python3
# Copyright 2022 Canonical Ltd.
#
# 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.
#
# For those usages not covered by the Apache License, Version 2.0 please
# contact: legal@canonical.com
#
# To get in touch with the maintainers, please contact:
# osm-charmers@lists.launchpad.net
#
#
# Learn more at: https://juju.is/docs/sdk

"""OSM Temporal charm.

See more: https://charmhub.io/osm
"""

import logging
import os
import socket

from log import log_event_handler
from typing import Any, Dict

from charms.observability_libs.v1.kubernetes_service_patch import KubernetesServicePatch
from charms.osm_libs.v0.utils import (
    CharmError,
    check_container_ready,
    check_service_active,
)
from charms.osm_temporal.v0.temporal import TemporalProvides
from lightkube.models.core_v1 import ServicePort
from ops.charm import CharmBase, LeaderElectedEvent, RelationJoinedEvent
from ops.framework import StoredState
from ops.main import main
from ops.model import ActiveStatus, Container

from legacy_interfaces import MysqlClient

logger = logging.getLogger(__name__)
SERVICE_PORT=7233


class OsmTemporalCharm(CharmBase):
    """OSM Temporal Kubernetes sidecar charm."""

    _stored = StoredState()
    container_name = "temporal"
    service_name = "temporal"

    def __init__(self, *args):
        super().__init__(*args)

        self.db_client = MysqlClient(self, "db")
        self._observe_charm_events()
        self.container: Container = self.unit.get_container(self.container_name)
        self._stored.set_default(leader_ip="")
        self._stored.set_default(unit_ip="")
        self.temporal = TemporalProvides(self)
        self._patch_k8s_service()

    # ---------------------------------------------------------------------------
    #   Handlers for Charm Events
    # ---------------------------------------------------------------------------

    @log_event_handler(logger)
    def _on_config_changed(self, event) -> None:
        """Handler for the config-changed event."""
        try:
            self._validate_config()
            self._check_relations()

            if self.unit.is_leader():
                leader_ip_value = socket.gethostbyname(socket.gethostname())
                if leader_ip_value and leader_ip_value != self._stored.leader_ip:
                    self._stored.leader_ip = leader_ip_value

            unit_ip_value = socket.gethostbyname(socket.gethostname())
            if unit_ip_value and unit_ip_value != self._stored.unit_ip:
                self._stored.unit_ip = unit_ip_value

            # Check if the container is ready.
            # Eventually it will become ready after the first pebble-ready event.
            check_container_ready(self.container)
            self._configure_service(self.container)
            self._update_temporal_relation()

            # Update charm status
            self._on_update_status(event)
        except CharmError as e:
            logger.error(e.message)
            self.unit.status = e.status

    @log_event_handler(logger)
    def _on_update_status(self, _=None) -> None:
        """Handler for the update-status event."""
        try:
            self._validate_config()
            self._check_relations()
            check_service_active(self.container, self.service_name)
            self.unit.status = ActiveStatus()
        except CharmError as e:
            logger.error(e.message)
            self.unit.status = e.status

    @log_event_handler(logger)
    def _on_required_relation_broken(self, event) -> None:
        """Handler for the kafka-broken event."""
        # Check Pebble has started in the container
        try:
            check_container_ready(self.container)
            check_service_active(self.container, self.service_name)
            self.container.stop(self.container_name)
        except CharmError:
            pass
        self._on_update_status(event)

    # ---------------------------------------------------------------------------
    #   Validation and configuration and more
    # ---------------------------------------------------------------------------

    def _observe_charm_events(self) -> None:
        event_handler_mapping = {
            # Core lifecycle events
            self.on.temporal_pebble_ready: self._on_config_changed,
            self.on.config_changed: self._on_config_changed,
            self.on.update_status: self._on_update_status,
            self.on.temporal_relation_joined: self._update_temporal_relation,
        }

        # Relation events
        for relation in [self.on[rel_name] for rel_name in ["db"]]:
            event_handler_mapping[relation.relation_changed] = self._on_config_changed
            event_handler_mapping[relation.relation_broken] = self._on_required_relation_broken

        for event, handler in event_handler_mapping.items():
            self.framework.observe(event, handler)

    def _validate_config(self) -> None:
        """Validate charm configuration.

        Raises:
            CharmError: if charm configuration is invalid.
        """
        logger.debug("validating charm config")

    def _check_relations(self) -> None:
        """Validate charm relations.

        Raises:
            CharmError: if charm configuration is invalid.
        """
        logger.debug("check for missing relations")
        missing_relations = []

        if not self.config.get("mysql-uri") and self.db_client.is_missing_data_in_unit():
            missing_relations.append("db")

        if missing_relations:
            relations_str = ", ".join(missing_relations)
            one_relation_missing = len(missing_relations) == 1
            error_msg = f'need {relations_str} relation{"" if one_relation_missing else "s"}'
            logger.warning(error_msg)
            raise CharmError(error_msg)

    def _update_temporal_relation(self, event: RelationJoinedEvent = None) -> None:
        """Handler for the temporal-relation-joined event."""
        logger.info(f"isLeader? {self.unit.is_leader()}")
        if self.unit.is_leader():
            self.temporal.set_host_info(self.app.name, SERVICE_PORT, event.relation if event else None)
            logger.info(f"temporal host info set to {self.app.name} : {SERVICE_PORT}")

    def _patch_k8s_service(self) -> None:
        port = ServicePort(SERVICE_PORT, name=f"{self.app.name}")
        self.service_patcher = KubernetesServicePatch(self, [port])

    def _configure_service(self, container: Container) -> None:
        """Add Pebble layer with the temporal service."""
        logger.debug(f"configuring {self.app.name} service")
        logger.info(f"{self._get_layer()}")
        container.add_layer("temporal", self._get_layer(), combine=True)
        container.replan()

    def _get_layer(self) -> Dict[str, Any]:
        """Get layer for Pebble."""
        return {
            "summary": "Temporal layer",
            "description": "pebble config layer for Temporal",
            "services": {
                self.service_name: {
                    "override": "replace",
                    "summary": "temporal service",
                    "command": "/etc/temporal/entrypoint.sh autosetup",
                    "startup": "enabled",
                    "user": "root",
                    "group": "root",
                    "ports": [7233,],
                    "environment": {
                        "DB": "mysql",
                        "DB_PORT": self.db_client.port,
                        "MYSQL_PWD": self.db_client.root_password,
                        "MYSQL_SEEDS": self.db_client.host,
                        "MYSQL_USER": "root",
                        "MYSQL_TX_ISOLATION_COMPAT": "true",
                        "BIND_ON_IP": "0.0.0.0",
                        "TEMPORAL_BROADCAST_ADDRESS": self._stored.unit_ip,
                    },
                },
            },
        }


if __name__ == "__main__":  # pragma: no cover
    main(OsmTemporalCharm)
