#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: __init__.py 9439 2015-09-25 08:01:30Z Eric $
#
# Copyright (c) 2015 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Eric $ (last)
# $Date: 2015-09-25 16:01:30 +0800 (Fri, 25 Sep 2015) $
# $Revision: 9439 $

class CeleryBrokerInfo(object):
    """
    Structure to store celery broker informations.
    """

    # We make all cloud machines with the same configuration to simplify
    # deployment and connection logic.
    BROKER_PORT = 5672
    BROKER_USER = 'celery'
    BROKER_PASSWORD = '25025529'
    BROKER_VHOST = '/'

    REDIS_PORT = 6379
    REDIS_PASSWORD = '25025529'

    def __init__(self, host, config=None):
        """
        Constructor.

        @param host Host public DNS name.
        @param config Configuration dictionary.
        """
        self.host = host

        default = {
            'BROKER_PORT': self.BROKER_PORT,
            'BROKER_USER': self.BROKER_USER,
            'BROKER_PASSWORD': self.BROKER_PASSWORD,
            'BROKER_VHOST': self.BROKER_VHOST,

            'CELERY_REDIS_PORT': self.REDIS_PORT,
            'CELERY_REDIS_PASSWORD': self.REDIS_PASSWORD,
        }

        if not config:
            config = default
        else:
            default.update(config)
            config = default

        self.port = config['BROKER_PORT']
        self.user = config['BROKER_USER']
        self.password = config['BROKER_PASSWORD']
        self.vhost = config['BROKER_VHOST']

        self.redisPort = config['CELERY_REDIS_PORT']
        self.redisPassword = config['CELERY_REDIS_PASSWORD']

class BackendMixin(object):
    """
    Mixin for queue service backend implementations.
    """

    # Pre-configured services for celery broker.
    CELERY_BROKER_SERVICES = ('rabbitmq', 'redis')

    # Celery broker configuration attribute, if it is not None, it will be
    # passed to CeleryBrokerInfo.
    CELERY_BROKER_CONFIGS = None

    def getCeleryBrokerInfo(self, preferred=None):
        """
        Get celery broker info instance.

        @param preferred Preferred machines.
        @return CeleryBrokerInfo.
        """
        domains = self.getDomains(preferred)
        for domain in domains:
            if self._checkStatus(domain, self.CELERY_BROKER_SERVICES):
                config = None
                if self.CELERY_BROKER_CONFIGS:
                    config = self.CELERY_BROKER_CONFIGS.get(domain, None)

                return CeleryBrokerInfo(domain, config=config)
        return None
