#! /usr/bin/env python3

import logging
import subprocess

from jinja2 import Template
from ops.charm import CharmBase
from ops.framework import StoredState
from ops.main import main
from ops.model import ActiveStatus, MaintenanceStatus


SQUID_CONF = "/etc/squid/squid.conf"

logger = logging.getLogger(__name__)


def reload():
    subprocess.Popen("sleep 1 && kill -HUP `cat /var/run/squid.pid`", shell=True)


def apply_config(config):
    with open(SQUID_CONF, "w") as f:
        f.write(config)
    reload()


def _generate_allowedurls_config(allowed_urls: set):
    allowed_urls_text = ""
    for url in allowed_urls:
        allowed_urls_text += f"acl allowedurls dstdomain .{url}\n"
    allowed_urls_text += "http_access allow allowedurls\n"
    return allowed_urls_text


def _generate_config(**kwargs):
    with open("template/squid.conf") as template:
        return Template(template.read()).render(**kwargs)


def update_config(allowed_urls: set):
    allowed_urls_config = _generate_allowedurls_config(allowed_urls)
    squid_config = _generate_config(allowed_urls=allowed_urls_config)
    if squid_config:
        apply_config(squid_config)


class SquidK8SCharm(CharmBase):
    """Class reprisenting this Operator charm."""

    _stored = StoredState()

    def __init__(self, *args):
        """Initialize charm and configure states and events to observe."""
        super().__init__(*args)
        self._stored.set_default(allowedurls=set())

        self.framework.observe(self.on.start, self.configure_pod)
        self.framework.observe(self.on.config_changed, self.configure_pod)
        self.framework.observe(self.on.addurl_action, self.on_addurl_action)
        self.framework.observe(self.on.deleteurl_action, self.on_deleteurl_action)

#        self.framework.observe(self.on["prometheus-target"].relation_joined, self._publish_prometheus_target_info)
    
#    def _publish_prometheus_target_info(self, event):
#        event.relation.data[self.unit]["host"] = self.app.name
#        event.relation.data[self.unit]["port"] = str(9100)

    def on_addurl_action(self, event):
        url = event.params["url"]
        self._stored.allowedurls.add(url)
        update_config(self._stored.allowedurls)

    def on_deleteurl_action(self, event):
        """Handle the deleteurl action."""
        url = event.params["url"]
        if url in self._stored.allowedurls:
            self._stored.allowedurls.remove(url)
            update_config(self._stored.allowedurls)

    def configure_pod(self, event):
        if not self.unit.is_leader():
            self.unit.status = ActiveStatus()
            return

        self.unit.status = MaintenanceStatus("Applying pod spec")

        pod_spec = {
            "version": 3,
            "containers": [
                {
                    "name": self.framework.model.app.name,
                    "image": "domfleischmann/squid-python",
                    "ports": [
                        {
                            "name": "squid",
                            "containerPort": self.config["port"],
                            "protocol": "TCP",
                        }
                    ],
                },
 #               {
 #                   "name": "exporter",
 #                   "image": "prom/node-exporter",
 #                   "ports": [
 #                       {
 #                           "containerPort": 9100,
 #                           "name": "exporter-http",
 #                           "protocol": "TCP",
 #                       }
 #                   ],
 #               }
            ],
        }

        self.model.pod.set_spec(pod_spec)
        self.unit.status = ActiveStatus()
        self.app.status = ActiveStatus()


if __name__ == "__main__":
    main(SquidK8SCharm)
