# -*- coding: utf-8 -*-
from werkzeug.datastructures import ImmutableDict
from flask import current_app
import importlib
import imp


class NSQ(object):
    default_config = ImmutableDict({
        'NSQ_CLIENT_TYPE': None,
        'NSQ_ADDRESS': 'localhost',
        'NSQ_DAEMON_PORT': 4150,
        'NSQ_READER_PORT': 4151
    })

    supported_clients = ['gnsq', 'pynsq']

    def __init__(self, app=None, daemon_config=None):
        self.app = app
        if app is not None:
            self.init_app(app, daemon_config)

    def init_app(self, app):
        for key, value in self.default_config:
            app.config.setdefault(key, value)

        if app.config['CLIENT_TYPE'] not in self.supported_clients:
            raise Exception('Invalid NSQ client library, valid values are %s, %s' % (
                self.supported_clients[0], self.supported_clients[1]))

        if app.config['CLIENT_TYPE'] == 'gnsq':
            client = GNSQ()
        elif app.config['CLIENT_TYPE'] == 'pynsq':
            client = PYNSQ

        # setup a new connection to the daemon
        daemon = client.daemon(app.config['NSQ_ADDRESS'], app.config['NSQ_DAEMON_PORT'],
                               daemon_config)

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        app.extensions.setdefault('nsq', {})
        app.extensions['nsq']['client'] = client
        app.extensions['nsq']['daemon'] = daemon

    @property
    def client(self):
        app = self.app or current_app
        return app.extensions['nsq']['client']

    @property
    def daemon(self):
        app = self.app or current_app
        return app.extensions['nsq']['daemon']

    def create_reader(self, topic, channel, reader_config):
        app = self.app or current_app
        reader = self.client.reader(app.config['NSQ_ADDRESS'],
                                    app.config['NSQ_READER_PORT'],
                                    topic, channel, reader_config)

    def _store_reader(self, topic, channel, reader):
        ext = (self.app or current_app).extensions['nsq']
        if not ext.get(topic):
            ext.setdefault(topic, {})

        ext[topic][channel] = reader

    def get_reader(self, topic, channel):
        ext = (self.app or current_app).extensions['nsq']
        return ext[topic][channel]


class NSQClient(object):
    def __init__(self, client_name):
        # check of existense of client
        try:
            imp.find_module(client_name)
        except Exception:
            raise Exception('Unable to find NSQ client library %s' % (client_name))


class GNSQ(NSQClient):
    def __init__(self):
        super(GNSQ, self).__init__('gnsq')

    @classmethod
    def daemon(cls, address, port, daemon_config):
        import gnsq.Nsqd
        if daemon_config.get('address'):
            add = daemon_config.pop('address')
        else:
            add = address

        if daemon_config.get('http_port'):
            p = daemon_config.pop('http_port')
        else:
            p = port

        return Nsqd(add, http_port=p, **daemon_config)

    @classmethod
    def reader(cls, address, port, topic, channel, reader_config):
        import gnsq.Reader
        if reader_config.get('nsqd_tcp_addresses'):
            add = reader_config.pop('nsqd_tcp_addresses')
        else:
            add = '%s:%s' % (address, port)
        return Reader(topic, channel, add, reader_config)


class PYNSQ(NSQClient):
    def __init__(self):
        super(GNSQ, self).__init__('nsq')

@@ -101,25 +101,8 @@
 app%0A
-import importlib%0A
 impo
@@ -117,18 +117,18 @@
 %0Aclass N
-SQ
+sq
 (object)
@@ -398,20 +398,18 @@
 _config=
-None
+%7B%7D
 ):%0A     
@@ -527,16 +527,34 @@
 elf, app
+, daemon_config=%7B%7D
 ):%0A     
@@ -593,16 +593,28 @@
 t_config
+.iteritems()
 :%0A      
@@ -669,32 +669,36 @@
  if app.config%5B'
+NSQ_
 CLIENT_TYPE'%5D no
@@ -899,32 +899,36 @@
  if app.config%5B'
+NSQ_
 CLIENT_TYPE'%5D ==
@@ -958,19 +958,19 @@
 ient = G
-NSQ
+nsq
 ()%0A     
@@ -989,16 +989,20 @@
 config%5B'
+NSQ_
 CLIENT_T
@@ -1041,20 +1041,22 @@
 ient = P
-YNSQ
+ynsq()
 %0A%0A      
@@ -1745,32 +1745,35 @@
 l, reader_config
+=%7B%7D
 ):%0A        app =
@@ -1985,32 +1985,105 @@
 , reader_config)
+%0A        self._store_reader(topic, channel, reader)%0A        return reader
 %0A%0A    def _store
@@ -2431,18 +2431,18 @@
 %0Aclass N
-SQ
+sq
 Client(o
@@ -2698,23 +2698,23 @@
 %0Aclass G
-NSQ(NSQ
+nsq(Nsq
 Client):
@@ -2745,35 +2745,35 @@
 %0A        super(G
-NSQ
+nsq
 , self).__init__
@@ -2858,28 +2858,38 @@
         
+from gnsq.nsqd 
 import 
-gnsq.
 Nsqd%0A   
@@ -3292,20 +3292,32 @@
     
+from gnsq.reader 
 import 
-gnsq.
 Read
@@ -3558,16 +3558,16 @@
 ss P
-YNSQ(NSQ
+ynsq(Nsq
 Clie
@@ -3613,12 +3613,13 @@
 per(
-GNSQ
+Pynsq
 , se

Fix class names Fix import errors