from Qt import QtCore, QtWidgets, QtGui
import logging
log = logging.getLogger("wizart_desktop")
import pika
import qt_utils
import time
from pika.exceptions import *


class UpdateQueueThread(QtCore.QThread):
    RABBITMQ_HOST = "scm.burut.net"
    EXCHANGE_NAME = "wizart_desktop_update"

    def __init__(self):
        super(UpdateQueueThread, self).__init__()

    def __callback(self, ch, method, properties, body):
        if body == "force_restart":
            log.info("Received 'force_restart' command from '%s'" % self.RABBITMQ_HOST)
            qt_utils.restart_app()
        elif body == "rescan_projects_config":
            log.info("Received 'rescan_projects_config' command from '%s'" % self.RABBITMQ_HOST)
            qt_utils.rescan_projects_config()

    def connect_and_consume(self):
        try:
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.RABBITMQ_HOST, heartbeat = 0 ))
            log.info("Connected to wizart_desktop_update service '%s': %s" % (self.RABBITMQ_HOST, self.connection))
            self.channel = self.connection.channel()
            self.channel.exchange_declare(exchange=self.EXCHANGE_NAME,exchange_type='fanout')
            result = self.channel.queue_declare(exclusive=True)
            self.queue_name = result.method.queue
            self.channel.queue_bind(exchange=self.EXCHANGE_NAME, queue=self.queue_name)
            self.channel.basic_consume(self.__callback, queue = self.queue_name, no_ack=True)
            self.channel.start_consuming()
        except AMQPError as e:
            log.warning("Wizart_desktop_update connection error", exc_info = True)

    def run(self):
        while True:
            self.connect_and_consume()
            #try to reconnect every 60 seconds
            time.sleep(60)
