from yasi_applets.software import bp
from flask import Flask, request, session, redirect, \
     url_for, render_template, flash, Blueprint
import gettext
# we use this neat little trick to get config data from the main app
from flask import current_app

# Set up Gettext
def set_language(LANG):
    """
    Sets language for this applet
    """
    translations = gettext.translation("users", '/usr/share/yasi-daemon/yasi_applets/users/locales',
                                       fallback=True, languages=[LANG])
    translations.install()
    _ = translations.gettext

set_language('')


@bp.route('/users')
def users_root():
    """
    Users screen for the webui.
    """
    set_language(current_app.config['CONFIG']['settings']['language'])
    string_dict = build_stringlist()
    build_menu()
    menu = current_app.config['CONFIG']['settings']['menu_order'].split(" ")
    next_step_url = menu[menu.index("users")+1]
    if menu[menu.index("users")] == 1:
        previous_step_url = False
    else:
        previous_step_url = menu[menu.index("users")-1]

    root_button = '&nbsp; <button class="button not-allowed is-light"> <i class="fa fa-user" aria-hidden="true"></i> &nbsp; Setup root user </button>'
    ldap_button = '&nbsp; <button class="button is-light"> <i class="fa fa-address-card" aria-hidden="true"></i> &nbsp; Connect LDAP </button>'
    ad_button = '&nbsp; <button class="button is-light"> <i class="fa fa-address-card" aria-hidden="true"></i> &nbsp; Connect AD </button>'
    csv_button = '&nbsp; <button class="button is-light"> <i class="fa fa-users" aria-hidden="true"></i> &nbsp; Import CSV </button>'
    bottom_menu = root_button + ldap_button + ad_button + csv_button
    bottom_menu = ""

    initial_user = current_app.config['CONFIG']['recipe']['users']['users'][0]

    build_summary()

    return render_template('users.html', string_dict=string_dict,
                           menu=current_app.config['CONFIG']['settings']['menu'],
                           menu_order=current_app.config['CONFIG']['settings']['menu_order'].split(),
                           previous_step=previous_step_url,
                           next_step=next_step_url,
                           bottom_menu=bottom_menu,
                           initial_user=initial_user)


@bp.route('/users/user-check/', methods=['GET', 'POST', 'PUT'])
def check_user():
    if request.method == 'POST':
        username = request.form["username"]
        fullname = request.form["fullname"]
        current_app.config['CONFIG']['recipe']['users']['users'][0]['username'] = username
        current_app.config['CONFIG']['recipe']['users']['users'][0]['fullname'] = fullname
        if username in ["root", "games"]:
            return('<p class="has-text-danger"><b>That username is not available</b> </p>')
        else:
            return('<p class="has-text-success"><b>That username is available</b> </p>')
        build_summary()
    return("")


@bp.route('/users/password-check/', methods=['GET', 'POST', 'PUT'])
def check_password():
    if request.method == 'POST':
        password = request.form["password"]
        password_confirm = request.form["password_confirm"]
        current_app.config['CONFIG']['recipe']['users']['users'][0]['password'] = password
        current_app.config['CONFIG']['recipe']['users']['users'][0]['password_confirm'] = password_confirm
        if password != password_confirm:
            return('<p class="has-text-danger"><b>Passwords do not match</b> </p>')
        else:
            return('<p class="has-text-success"><b>Passwords match</b> </p>')
        build_summary()
    return("")


def build_stringlist():
    """
    Return all the strings that is used in this applet.
    """
    string_dict = {}
    string_dict['menu_item'] = _("Users")
    string_dict['initial_user_text'] = _("Let's set up an initial user.")
    string_dict['full_name'] = _("Full Name")
    string_dict['user_name'] = _("Username")
    string_dict['user_name_hint'] = _("One word, all lowercase")
    string_dict['user_name_available'] = _("This username is available")
    string_dict['user_name_not_available'] = _("This username is not available")
    string_dict['user_name_reserved'] = _("This username is reserved by the system")
    string_dict['user_name_characters'] = _("The username must be one word, lowercase, with no special characters")
    string_dict['password'] = _("Password")
    string_dict['password_confirm'] = _("Password (confirm)")
    string_dict['password_nomatch'] = _("These passwords do now match")
    string_dict['password_tooshort'] = _("This password is too short")
    string_dict['next_text'] = _("Next")
    string_dict['back_text'] = _("Back")
    return string_dict


def build_menu():
    """
    Define menu items and paths.
    """
    current_app.config['CONFIG']['settings']['menu']['users'] = (build_stringlist()['menu_item'], "/users", 20)


def build_summary():
    """
    Write up a summary of what this module will do.
    """
    current_app.config['CONFIG']['Summary']['users'] = {}
    current_app.config['CONFIG']['Summary']['users']['heading'] = "Users and Identity"
    current_app.config['CONFIG']['Summary']['users']['settings'] = current_app.config['CONFIG']['recipe']['users']['users']
    current_app.config['CONFIG']['Summary']['users']['text'] = "Add primary user with the username: " + str(current_app.config['CONFIG']['recipe']['users']['users'][0]['username'])
    return("ok?")

build_menu()
