import databases
from motor import motor_asyncio
from arq import ArqRedis, create_pool
from arq.connections import RedisSettings
from sanic import Sanic

mongo_client: motor_asyncio.AsyncIOMotorClient = None
mongo_db: motor_asyncio.AsyncIOMotorDatabase = None
redis: ArqRedis = None


def create_app(config):
    # global
    app = Sanic(name=config['name'])
    app.config.from_object(config)

    app.pg_db = databases.Database(config['PSQL_URL'])

    app.listeners['after_server_start'].extend([setup_motor, setup_arq])

    app.listeners['before_server_stop'].extend([close_motor, close_arq])

    from .api.v1 import bpg
    app.register_blueprint(bpg)

    from .models import init_orm
    init_orm(app.pg_db)

    return app


async def setup_arq(app, loop):
    global redis
    redis = await create_pool(RedisSettings())


async def close_arq(app, loop):
    global redis
    redis.close()
    await redis.wait_closed()


async def setup_database(app, loop):
    await app._database.connect()


async def close_database(app, loop):
    await app._databases.disconnect()


async def setup_motor(app, loop):
    global mongo_client, mongo_db
    mongo_client = motor_asyncio.AsyncIOMotorClient(
        "mongodb://localhost:27017", io_loop=loop)
    mongo_db = mongo_client['test']


async def close_motor(app, loop):
    global mongo_client
    mongo_client.close()


# def make_arq(config):
#     global redis
#     redis = create_pool(RedisSettings())
#     return redis

@@ -276,16 +276,49 @@
  = None%0A
+pg_db: databases.Database = None%0A
 %0A%0Adef cr
@@ -342,17 +342,21 @@
 %0A   
- #
  global
+ pg_db
 %0A   
@@ -383,16 +383,13 @@
 nfig
-%5B'
+.
 name
-'%5D
 )%0A  
@@ -421,25 +421,20 @@
 config)%0A
-%0A
     
-app.
 pg_db = 
@@ -452,16 +452,20 @@
 atabase(
+app.
 config%5B'
@@ -469,11 +469,9 @@
 g%5B'P
-SQL
+G
 _URL
@@ -522,16 +522,25 @@
 .extend(
+%0A        
 %5Bsetup_m
@@ -550,24 +550,40 @@
 r, setup_arq
+, setup_database
 %5D)%0A%0A    app.
@@ -621,16 +621,25 @@
 .extend(
+%0A        
 %5Bclose_m
@@ -653,16 +653,32 @@
 lose_arq
+, close_database
 %5D)%0A%0A    
@@ -738,66 +738,8 @@
 g)%0A%0A
-    from .models import init_orm%0A    init_orm(app.pg_db)%0A%0A
     
@@ -989,35 +989,44 @@
 p):%0A    
-await app._database
+global pg_db%0A    await pg_db
 .connect
@@ -1075,28 +1075,36 @@
     
-await app._databases
+global pg_db%0A    await pg_db
 .dis

fix init bug