import os
import pika
import configparser


def read_config():
    config = configparser.ConfigParser()
    path = os.getenv("CFG_PATH")
    if not path:
        path = os.path.dirname(__file__) + "/config.cfg"
        print("case default:"+path)
        config.read(path)
    else:
        print("case in env: "+path)
        config.read(path)
    return config


class RabbitMQClient:
    connection = None
    channel = None
    credentials = None

    def __init__(self):
        config = read_config()
        user = config.get('SATELLITE_KEYS', 'USER_NAME')
        password = config.get('SATELLITE_KEYS', 'USER_PASSWORD')
        host = config.get('SATELLITE_KEYS', 'HOST_IP')

        self.credentials = pika.PlainCredentials(user, password)
        self.try_connect(host)

    def try_connect(self, host):
        try:
            self.connection = pika.BlockingConnection(
                pika.ConnectionParameters(host=host, credentials=self.credentials))
            self.channel = self.connection.channel()
        except Exception:
            raise Exception("cannot establish connection with RabbitMQ")

    def send_message(self, message, exchange_name):
        try:
            exchange_id, routing_key = RabbitMQClient.get_exchange_params(exchange_name)
            self.channel.exchange_declare(exchange=exchange_id, exchange_type='fanout')
            self.channel.basic_publish(exchange=exchange_id, routing_key=routing_key,
                                       body=message)
            print(" [x] Sent %r" % message)
        except Exception:
            raise Exception("Connection is not established")

    def close_connection(self):
        try:
            self.connection.close()
        except Exception:
            raise Exception("Connection is not established")

    @staticmethod
    def get_exchange_params(exchange_name):
        routing_key = os.getenv('SATELLITE_ID')
        if exchange_name.lower() == "tracker":
            exchange_name = os.getenv("SATELLITE_GROUP")
        elif exchange_name.lower() == "resources":
            exchange_name = os.getenv("RESOURCES_EXCHANGE")
        else:
            exchange_name = None
        return exchange_name, routing_key
