import os
import re

from fab_deploy2 import functions
from fab_deploy2.config import CustomConfig
from fab_deploy2.tasks import ServiceContextTask, task_method

from fabric.api import run, sudo, env, put, local
from fabric.contrib.files import append, exists

from jinja2.exceptions import TemplateNotFound

class Collectd(ServiceContextTask):
    """
    Sync a collectd config
    """

    name = 'setup'
    context_name = 'collectd'
    namespace = 'collectd'

    default_context = {
        'template' : 'collectd/collectd.conf',
        'base_dir' : '/var/lib/collectd',
        'remote_config_path' : '/etc/collectd/collectd.conf',
        'plugin_configs' : '/etc/collectd/collectd.d/',
        'plugin_path' : '/usr/lib/collectd/',
        'types_db' : '/usr/share/collectd/types.db',
        'config_section' : 'collectd-receiver',
        'interval' : 20,
        'base_plugins' : ('cpu', 'load', 'interface', 'logfile', 'df',
                          'disk','processes','swap', 'tcpconns', 'memory',
                          'network', 'threshold'),
        'package_name' : 'collectd',
        'package_names' : None,
        'timeout' : 2,
        'threads' : 5,
        'collectd_tar' : 'collectd-5.4.0'
    }

    def _add_package(self, name):
        raise NotImplementedError()

    def _plugin_context(self, plugin):
        data = {}
        context_func = '{0}_context'.format(plugin)
        if hasattr(self, context_func):
            data.update(getattr(self, context_func)())
        data.update(self._get_plugin_env_context(plugin))
        return data

    def _get_plugin_env_context(self, plugin):
        key = 'collectd_{0}'.format(plugin)
        data = env.context.get(key, {})
        role = env.host_roles.get(env.host_string)
        if role:
            role_dict = functions.get_role_context(role)
            data.update(role_dict.get(key, {}))
        return data

    def _install_plugin(self, plugin, context, **kwargs):
        task_name = 'collectd.{0}_setup'.format(plugin)
        task = functions.get_task_instance(task_name)
        package_names = self.package_names
        if task:
            functions.execute_on_host(task_name, **kwargs)
        else:
            if package_names and plugin in package_names:
                self._add_package(package_names[plugin])

            self.render_plugin_configs(plugin, context, **kwargs)

    def render_plugin_configs(self, plugin, context, **overides):
        if not env.task_context.get(env.host_string + 'pdir'):
            sudo('mkdir -p {0}'.format(self.plugin_configs))