#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: __init__.py 9476 2015-11-10 08:55:23Z Judy $
#
# 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: Judy $ (last)
# $Date: 2015-11-10 16:55:23 +0800 (Tue, 10 Nov 2015) $
# $Revision: 9476 $

from celery import Celery
from Iuno.cloud import tryGet

def attachSettings(settingsLocals, backends, preferred, config):
    """
    Attach 'queue' related settings to settings.py.

    @param settingsLocals locals() in settings.py.
    @param backends Backend instances.
    @param preferred Preferred backends.
    @param config Configuration settings.
    """
    hostInfo = tryGet('getCeleryBrokerInfo', backends, preferred)
    if not hostInfo:
        raise RuntimeError('There are no available brokers.')

    settingsLocals.update({
        'BROKER_URL': 'amqp://{user}:{password}'
                      '@{host}:{port}{vHost}'.format(
                         user=hostInfo.info.user,
                         password=hostInfo.info.password,
                         host=hostInfo.info.host,
                         port=hostInfo.info.port,
                         vHost=hostInfo.info.vhost                         
                       ),                   
        
        'CELERY_RESULT_BACKEND': 'redis://:{password}'
                                 '@{host}:{port}'.format(
                                    password=hostInfo.info.redisPassword,
                                    host=hostInfo.info.host,
                                    port=hostInfo.info.redisPassword
                                 ),
        'CELERY_TASK_SERIALIZER': 'pickle',
        'CELERY_RESULT_SERIALIZER': 'pickle',
        'CELERY_ACCEPT_CONTENT': ['pickle'],
    })
 
    if 'CELERY_ROUTES' not in settingsLocals:
        settingsLocals['CELERY_ROUTES'] = {}
 
    # Shall we set BROKER_CONNECTION_RETRY, BROKER_CONNECTION_MAX_RETRIES
    # to retry broker connection, because of we setup monit to restart
    # broken service if needed?
 
    hostInfo.backend.attachSettings(settingsLocals)

def getDefaultPreferred(context=None):
    """
    Get default preferred backend sequence.

    @param context Settings context.
    @return Preferred backend names.
    """
    return (
        'Nuwa',
        'Local'
    )
