import os
import sys
import onapp.lib.log as log

sys.path.append('/home/mq/onapp/lib')
import pika
import yaml

class Connection:
    CREDENTIALS_FILE = '/home/mq/onapp/messaging/credentials.yml'
    LOCALHOST = 'localhost'
    PORT = 5672
    GUEST = 'guest'
    DEFAULT_Q = 'not_configured_hv'
    DEFAULT_X = {'name':'default',
                 'type':'direct',
                 'passive':False,
                 'durable':True,
                 'auto_delete':False}

    def __init__(self):
        self.credentials = c = self.read_credentials()

        self.host = c.get('host') or self.LOCALHOST
        self.port = int(c.get('port') or self.PORT)
        self.vhost = c.get('vhost') or '/'
        self.user = c.get('user') or self.GUEST
        self.password = c.get('password') or self.GUEST
        self.exchange = c.get('exchange') or self.DEFAULT_X
        self.queue = c.get('queue') or self.DEFAULT_Q

        if 'password' in c:
            del c['password']

        log.debug('Connecting with: %s' % c)

        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=self.host,
                port=self.port,
                virtual_host=self.vhost,
                credentials=pika.PlainCredentials(self.user, self.password)
            )
        )

    def read_credentials(self):
        # For Python > 2.6
        # with open(self.CREDENTIALS_FILE, 'r') as conn_settings:
        #     data = json.load(conn_settings)
        conn_settings = open(self.CREDENTIALS_FILE, 'r')
        try:
            data = yaml.load(conn_settings)
        finally:
            conn_settings.close()

        return data

    def open_channel(self):
        channel = self.connection.channel()

        channel.exchange_declare(
            exchange=self.exchange.get('name'),
            type=self.exchange.get('type'),
            passive=False,
            durable=True,
            auto_delete=False
        )
        channel.queue_declare(queue=self.queue)
        channel.queue_bind(queue=self.queue, exchange=self.exchange.get('name'))

        return channel

    def close(self):
        self.connection.close()
