#!/usr/bin/env python

from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database


# POSTGRESQL SETTINGS
GAL_DB = 'gal'
GIS_DB = 'datagis'
PG_USER = 'postgres'
PG_PASS = 'xx1171'
PG_HOST = 'localhost'

# DATABASE GAL
GAL_Base = declarative_base()
GAL_DATABASE = 'postgresql://' + PG_USER + ':' + PG_PASS + '@' + PG_HOST + '/' + GAL_DB
GAL_Engine = create_engine(GAL_DATABASE)
GAL_Cursor = GAL_Engine.connect()
GAL_Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=GAL_Engine))
GAL_Base.query = GAL_Session.query_property()


def init_gal():
    GAL_Base.metadata.create_all(bind=GAL_Engine)


# DATABASE GIS
GIS_Base = declarative_base()
GIS_DATABASE = 'postgresql://' + PG_USER + ':' + PG_PASS + '@' + PG_HOST + '/' + GIS_DB
GIS_Engine = create_engine(GIS_DATABASE, client_encoding='utf8')

if not database_exists(GIS_Engine.url):
    create_database(GIS_Engine.url)
    GIS_Engine.connect().execute("CREATE EXTENSION postgis")

GIS_Cursor = GIS_Engine.connect()
GIS_Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=GIS_Engine))
GIS_Base.query = GIS_Session.query_property()


def init_datagis():
    from models.datageo import Municipio
    GIS_Cursor.execute('''
    DROP TABLE IF EXISTS macrorregional, regional, municipio, municipio_regional, parana,
     arbovirus, arbovirus_geo, sintomatico, sintomatico_geo CASCADE ''')
    GIS_Base.metadata.create_all(bind=GIS_Engine)
