#!/usr/bin/env python

import os
import posixpath

import click
import logging
import requests
import yaml

from reading import config as cfg
from reading import controllers
from reading.models import Base


logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()


@click.group()
@click.option('--debug/--no-debug', default=False, help="Whether to run Flask in debug mode")
@click.option('-c', '--config', default=None, nargs=1, type=str, help="Path to config file")
@click.pass_context
def cli(ctx, debug, config):
    if config:
        with open(config, 'r') as configfile:
            cfg.set_config(yaml.load(configfile))
    else:
        cfg.set_config_from_env()
    ctx.obj = {'DEBUG': debug}


@cli.command()
@click.pass_context
def create_tables(ctx):
    """ Drop and create database """
    db = controllers.database.get_database_connection()
    db.drop_tables()
    db.create_tables()


@cli.command()
@click.argument('email', type=str)
@click.option('--administrator/--no-administrator', default=False, help="Should user be an admin?")
def add_user(email, administrator):
    db = controllers.database.get_database_connection()
    db.add_user(email, administrator, api_key=None)


@cli.command()
@click.pass_context
def serve(ctx):
    """ Start the webserver """
    from reading import web
    web.app.run(debug=ctx.obj['DEBUG'])


if __name__ == '__main__':
    cli()
