# -*- coding: utf-8 -*-
from __future__ import division
import click
import os
import collections
import contextlib
import signal
import swiftclient
import keystoneclient
import subprocess32 as subprocess
import copy
import sqlalchemy

AUTH_VERSION = 2

# An object which we can use to pass state 
# from the group to subcommands.
State = collections.namedtuple('state', ('verbose', 'engine'))

# Fall back to the usual sigpipe behaviour.
# This fixes cases of weird errors when you pipe to less.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

def echo_error(message):
    """A utility function to print the message to stderr."""

    click.secho(message, fg='red', err=True)

# ====================================
# Database Definitions
# ====================================

DEFAULT_DB_URL = 'sqlite:///swiftbulkuploader.db'

metadata = sqlalchemy.MetaData()

paths = sqlalchemy.Table('paths', metadata,
    sqlalchemy.Column('id', sqlalchemy.Integer, 
                            sqlalchemy.Sequence('paths_id_seq'), 
                            primary_key=True),
    sqlalchemy.Column('path', sqlalchemy.Text()),
    sqlalchemy.Column('pathtype', sqlalchemy.Enum('directory', 
                                                  'file')),
    sqlalchemy.Column('accessible', sqlalchemy.Boolean),
    sqlalchemy.Column('status', sqlalchemy.Enum('unprocessed', 
                                                'processed', 
                                                'error')),
    sqlalchemy.Column('bytes', sqlalchemy.BigInteger),
    sqlalchemy.Column('objectname', sqlalchemy.Text),
)

# ====================================
# Main Command Group
# ====================================

@click.group()
@click.option('--verbose', default=False, is_flag=True,
              help='Enable verbose output.')
@click.option('--db-url', default=DEFAULT_DB_URL,
              help='The sqlalchemy database URL to use. Default: {}'.format(
              DEFAULT_DB_URL))
@click.pass_context
def cli(ctx, verbose, db_url):
    if verbose:
        click.echo('Verbose mode on.')

    try:
        engine = sqlalchemy.create_engine(db_url, echo=verbose)
        metadata.create_all(engine) 
        if verbose: click.echo("Created table 'paths' if it did not exist.")        
        ctx.obj = State(verbose, engine)
    except sqlalchemy.exc.SQLAlchemyError as e:
        echo_error('Unable to connect to {}.'.format(db_url))
        echo_error('{}.'.format(e))
        raise click.Abort