# WatchGhost, your invisible but loud monitoring pet
# Copyright © 2015 Kozea

from collections import OrderedDict
from importlib import import_module
from uuid import uuid4

import logging

logger = logging.getLogger(__name__)


class Service:
    config = {
        'description': None,
        'repeat': 3600,
        'before': '23:59:59',
        'after': '00:00:00',
        'status': OrderedDict([
            ('info', [{'ok': True}]),
            ('critical', [{}])
        ]),
        'retry': 2,
        'retry_interval': 15,
    }

    def __init__(self, name):
        self.uuid = uuid4().hex
        self.name = name

        module_name, service_name = name.rsplit('.', 1)
        module = import_module('watchghost.services.{}'.format(module_name))
        self.cls = getattr(module, service_name)

        self.config = self.config.copy()
        self.config.update(self.cls.config)

        self.description = self.config['description']

    async def check(self, server, config):
        """Check the service and return the status.

        :return: A dictionary with various values corresponding to the status
            of the service. The default keys included in the dict are 'ok'
            (True if the service works, else False) and 'message' (a string
            describing the status).

        """
        try:
            response = await self.cls.check(server, config)
        except Exception as exception:
            logger.exception('exception occured in service')
            return {
                'ok': False,
                'message': 'An internal error occured: {}'.format(exception)}
        else:
            if 'ok' not in response:
                response['ok'] = False
            if 'message' not in response:
                response['message'] = 'No message'
            return response
