# -*- coding: utf-8 -*-

"""\
© Copyright. All rights reserved.

"""

from __future__ import unicode_literals

import logging
from subprocess import PIPE, call, CalledProcessError


LOGGER = logging.getLogger(__name__)


class BaseDaemon(object):
    """A base implementation of a daemon"""
    def __init__(self, name, command_fmt):
        self.name = name
        self.command_fmt = command_fmt

    def _run(self, action, check_return_code=True, pipes=True):
        LOGGER.info('%sing %s', action, self.name)
        kwargs = dict(universal_newlines=True, timeout=10)
        if pipes:
            kwargs.update(dict(stdout=PIPE, stderr=PIPE))
        cmd = self.command_fmt.format(name=self.name, action=action)
        result = call(cmd.split(), **kwargs)
        LOGGER.info(result)
        if check_return_code:
            if result != 0:
                raise CalledProcessError(returncode=result, cmd=cmd)
        return result

    def status(self):
        return self._run('status', check_return_code=False)

    def start(self):
        # Must not connect pipes to stdin/out, or subprocess will never
        # complete, hanging on communicate() call.
        return self._run('start', pipes=False)

    def stop(self):
        return self._run('stop')

    def restart(self):
        # Must not connect pipes to stdin/out, or subprocess will never
        # complete, hanging on communicate() call.
        return self._run('restart', pipes=False)
