# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import logging
from saas.library.python.nanny_rest.service_mutable_proxy.environment_variable import (
    from_nanny_dict, EnvironmentVariable, VaultSecretEnv
)


class UnistatEndpoint(object):
    __slots__ = ('path', 'port')

    def __init__(self, path, port):
        self.path = path
        self.port = port

    def dict(self):
        return {'path': self.path, 'port': self.port}

    def __repr__(self):
        return 'UnistatEndpoint({}, {})'.format(self.path, self.port)


class Container(object):
    LOGGER = logging.getLogger(__name__)

    __slots__ = ('instance_spec', 'name', 'command', 'env', 'unistatEndpoints', 'hostDevices', 'reopenLogAction',
                 'resourceRequest', 'restartPolicy', 'readinessProbe', 'securityPolicy', 'lifecycle', 'coredumpPolicy')

    def __init__(self, instance_spec, name, command=None, env=None, unistatEndpoints=None, hostDevices=None, reopenLogAction=None,
                 resourceRequest=None, restartPolicy=None, readinessProbe=None, securityPolicy=None,
                 lifecycle=None, coredumpPolicy=None):
        self.instance_spec = instance_spec
        self.name = name
        self.unistatEndpoints = [UnistatEndpoint(**u) for u in unistatEndpoints] if unistatEndpoints else []
        self.env = [from_nanny_dict(e) for e in env] if env else []

        self.command = command if command else []
        self.hostDevices = hostDevices if hostDevices else []
        self.reopenLogAction = reopenLogAction
        self.resourceRequest = resourceRequest
        self.readinessProbe = readinessProbe
        self.coredumpPolicy = coredumpPolicy
        self.restartPolicy = restartPolicy
        self.securityPolicy = securityPolicy
        self.lifecycle = lifecycle

    def dict(self):
        # instance spec is not really part of container so we don't need it in dict
        base_dict = {p: getattr(self, p) for p in self.__slots__ if p != 'instance_spec'}
        base_dict['unistatEndpoints'] = [e.dict() for e in base_dict['unistatEndpoints']]
        base_dict['env'] = [e.dict() for e in base_dict['env']]
        return {k: v for k, v in base_dict.items() if v is not None}

    @property
    def env_dict(self):
        return {e.name: e for e in self.env}

    def get_env(self, env_name):
        name_env_map = self.env_dict
        if env_name in name_env_map:
            return name_env_map[env_name]
        else:
            return None

    def ensure_env(self, env):
        env = env if isinstance(env, EnvironmentVariable) else from_nanny_dict(env)
        existing_env = self.get_env(env.name)
        if existing_env:
            if env != existing_env:
                raise ValueError('Partial duplicate {} found for {}'.format(existing_env, env))
            else:
                self.LOGGER.info('{} already present in service {}'.format(env, self.instance_spec.nanny_service))
        else:
            self.add_env(env)

    def add_env(self, env):
        env = env if isinstance(env, EnvironmentVariable) else from_nanny_dict(env)
        existing_env = self.get_env(env.name)
        if existing_env:
            raise ValueError('Volume {} already present'.format(existing_env))
        else:
            if isinstance(env, VaultSecretEnv):
                self.instance_spec._process_vault_secret(env)
            self.env.append(env)
