# -*- coding: UTF-8 -*


"""Application Flask: ScoDoc


"""


from __future__ import print_function

import os
from pprint import pprint as pp
import sys

import click
import flask
from flask.cli import with_appcontext
from app import create_app, cli, db

from app.auth.models import User, Role, UserRole
from app.views import notes, scolar, absences
import app.utils as utils

from config import Config


app = create_app()
cli.register(app)


@app.shell_context_processor
def make_shell_context():
    return {
        "db": db,
        "User": User,
        "Role": Role,
        "UserRole": UserRole,
        "notes": notes,
        "scolar": scolar,
        "pp": pp,
        "flask": flask,
        "current_app": flask.current_app,
    }


@app.cli.command()
def user_db_init():  # user-db-init
    """Initialize the users database."""
    click.echo("Init the db")
    # Create roles:
    Role.insert_roles()
    click.echo("created initial roles")
    # Ensure that admin exists
    if Config.SCODOC_ADMIN_MAIL:
        admin_user_name = Config.SCODOC_ADMIN_LOGIN
        user = User.query.filter_by(user_name=admin_user_name).first()
        if not user:
            user = User(user_name=admin_user_name, email=Config.SCODOC_ADMIN_MAIL)
            db.session.add(user)
            db.session.commit()
            click.echo(
                "created initial admin user, login: {u.user_name}, email: {u.email}".format(
                    u=user
                )
            )


@app.cli.command()
def user_db_clear():
    """Erase (drop) all tables of users database !"""
    click.echo("Erasing the users database !")
    _clear_users_db()


def _clear_users_db():
    """Erase (drop) all tables of users database !"""
    click.confirm("This will erase all users.\nDo you want to continue?", abort=True)
    db.reflect()
    db.drop_all()
    db.session.commit()


@app.cli.command()
@click.argument("username")
@click.argument("role")
@click.argument("dept")
def user_create(username, role, dept):  # user-create
    "Create a new user"
    r = Role.get_named_role(role)
    if not r:
        sys.stderr.write("user_create: role {r} does not exists\n".format(r=role))
        return 1
    u = User.query.filter_by(user_name=username).first()
    if u:
        sys.stderr.write("user_create: user {u} already exists\n".format(u=u))
        return 2
    if dept == "@all":
        dept = None
    u = User(user_name=username, dept=dept)
    u.add_role(r, dept)
    db.session.add(u)
    db.session.commit()
    click.echo(
        "created user, login: {u.user_name}, with role {r} in dept. {dept}".format(
            u=u, r=r, dept=dept
        )
    )


@app.cli.command()
@click.argument("username")
@click.password_option()
def user_password(username, password=None):  # user-password
    "Set (or change) user's password"
    if not password:
        sys.stderr.write("user_password: missing password")
        return 1
    u = User.query.filter_by(user_name=username).first()
    if not u:
        sys.stderr.write("user_password: user {} does not exists".format(username))
        return 1

    u.set_password(password)
    db.session.add(u)
    db.session.commit()
    click.echo("changed password for user {}".format(u))


@app.cli.command()
@click.argument("dept")
def sco_delete_dept(dept):
    "Delete existing departement"
    if os.getuid() != 0:
        sys.stderr.write("sco_delete_dept: must be run by root\n")
        return 1
    if os.system('cd config; ./delete_dept.sh -n "{}"'.format(dept)):
        sys.stderr.write("error deleting dept " + dept)
        return 1
    return 0


@app.cli.command()
@click.argument("dept")
def sco_create_dept(dept):
    "Create new departement"
    if os.getuid() != 0:
        sys.stderr.write("sco_create_dept: must be run by root\n")
        return 1
    if os.system('cd config; ./create_dept.sh -n "{}"'.format(dept)):
        sys.stderr.write("error deleting dept " + dept)
        return 1
    return 0


@app.cli.command()
@click.argument("filename")
@with_appcontext
def test_interactive(filename=None):
    "Run interactive test"
    import flask_login
    from app import decorators

    click.echo("Executing {}".format(filename))
    with app.test_request_context(""):
        u = User.query.first()
        flask_login.login_user(u)
        REQUEST = decorators.ZRequest()
        exec(open(filename).read())

    click.echo("Done.")


@app.cli.command()
@with_appcontext
def user_db_import_scodoc7():  # user-db-import-scodoc7
    """Import used defined in ScoDoc7 postgresql database into ScoDoc8
    The old database SCOUSERS  must be alive and readable by the current user.
    This script is typically run as unix user www-data.
    """
    utils.import_scodoc7_user_db()