# Path: plenario/database.py
# def create_database(bind: Engine, database: str) -> None:
# def drop_database(bind: Engine, database: str) -> None:
# def create_extension(bind: Engine, extension: str) -> None:
# def psql(path: str) -> None:
# def postgres_session_context():
# def redshift_session_context():


import logging
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from plenario.database import redshift_engine


logger = logging.getLogger(__name__)


def create_foi_table(foi_name, properties):
    """Create a new foi table
    
    :param foi_name: name of feature
    :param properties: list of {'name': name, 'type': type} dictionaries 
    """
    template = """
        CREATE TABLE {table} (
          "node_id" VARCHAR NOT NULL,
          "datetime" TIMESTAMP WITHOUT TIME ZONE NOT NULL,
          "meta_id" DOUBLE PRECISION NOT NULL,
          "sensor" VARCHAR NOT NULL,
          {props},
          PRIMARY KEY ("node_id", "datetime")
        )
        DISTKEY(datetime)
        SORTKEY(datetime);
    """
    kwargs = {
        'table': foi_name,
        'props': ', '.join('"{}" {}'.format(p['name'], p['type']) for p in properties)
    }

    operation = template.format(**kwargs)
    logger.info(operation)

# Path: plenario/database.py
# def create_database(bind: Engine, database: str) -> None:
# def drop_database(bind: Engine, database: str) -> None:
# def create_extension(bind: Engine, extension: str) -> None:
# def psql(path: str) -> None:
# def postgres_session_context():
# def redshift_session_context():


# Path: plenario/sensor_network/redshift_ops.py
import logging
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from plenario.database import redshift_engine



logger = logging.getLogger(__name__)


def create_foi_table(foi_name, properties):
    """Create a new foi table
    
    :param foi_name: name of feature
    :param properties: list of {'name': name, 'type': type} dictionaries 
    """
    template = """
        CREATE TABLE {table} (
          "node_id" VARCHAR NOT NULL,
          "datetime" TIMESTAMP WITHOUT TIME ZONE NOT NULL,
          "meta_id" DOUBLE PRECISION NOT NULL,
          "sensor" VARCHAR NOT NULL,
          {props},
          PRIMARY KEY ("node_id", "datetime")
        )
        DISTKEY(datetime)
        SORTKEY(datetime);
    """
    kwargs = {
        'table': foi_name,
        'props': ', '.join('"{}" {}'.format(p['name'], p['type']) for p in properties)
    }

    operation = template.format(**kwargs)
    logger.info(operation)

    redshift_engine.execute(text(operation))