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

# Set up Gettext
def set_language(LANG):
    """
    Sets language for this applet
    """
    # TODO: unhardcode this path
    translations = gettext.translation("welcome", './yasi_applets/welcome/locales',
                                       fallback=True, languages=[LANG])
    translations.install()
    _ = translations.gettext


@bp.route('/welcome',methods=['GET', 'POST', 'PUT'])
def welcome_index():
    """
    The page you'd get if you access the root of
    this app in a browser.
    """
    set_language(current_app.config['CONFIG']['settings']['language'])
    if request.method == 'POST':
        if "lang" in request.form.keys():
            current_app.config['CONFIG']['settings']['language'] = request.form["lang"]
            LANG = current_app.config['CONFIG']['settings']['language']
            set_language(LANG)
            FORMLANG = request.form["lang"]
        if "keyboard" in request.form.keys():
            print(request.form["keyboard"])
        if "timezone" in request.form.keys():
            print(request.form["timezone"])
    global lang
    lang = current_app.config['CONFIG']['settings']['language']
    set_language(lang)
    global string_dict
    string_dict = build_stringlist()
    blkid = lsblk.list_scsi_devices()
    build_menu()
    build_summary()
    menu = current_app.config['CONFIG']['settings']['menu_order'].split(" ")
    next_step_url = menu[menu.index("welcome")+1]
    previous_step_url = menu[menu.index("welcome")-1]

    print("index is: " , menu.index("welcome"))
    if menu.index("welcome") == 0:
        previous_step_url = False
    else:
        previous_step_url = menu[menu.index("users")-1]

    power_button = '<button id="powerbutton" hx-get="/welcome/battery/button" hx-trigger="load, every 1s" hx-target="#powerbutton" class="button is-dark"> <span style="color: #ffffff;"> <i class="fa fa-question" aria-hidden="true"></i></span> &nbsp;</button>'
    internet_button = '&nbsp; <button id="internetbutton" class="button is-dark" hx-get="/welcome/internet/button" hx-trigger="load, every 1s" hx-target="#internetbutton"><span style="color: #ffffff;"> <i class="fa fa-question" aria-hidden="true"></i></span> &nbsp;</button>'
    bottom_menu = power_button + internet_button


    return render_template('welcome.html',
                           string_dict=string_dict, selected_lang=lang,
                           menu=current_app.config['CONFIG']['settings']['menu'],
                           menu_order=current_app.config['CONFIG']['settings']['menu_order'].split(),
                           timezones=timezone.list_timezones()[1].split("\n"),
                           previous_step=previous_step_url,
                           next_step=next_step_url,
                           bottom_menu=bottom_menu)


@bp.route('/welcome/battery',methods=['GET', 'POST', 'PUT'])
def welcome_battery():
    """
    Are we running on battery?
    How much power do we have?
    """
    if "yes" in str(subprocess.check_output("LANG=C upower -d | grep on-battery", shell=True)):
       on_battery = True
    else:
       on_battery = False
    if on_battery:
        percentage = str(subprocess.check_output('LANG=C upower -d | grep '
                         'percentage | head -1 | cut -f 2 -d":" | '
                         'sed "s/ //g"', shell=True)).strip("'b").strip("%\\n")
    else:
        percentage = False
    status = {}
    status = {"on_battery": on_battery, "percentage": percentage}
    return status


@bp.route('/welcome/battery/button',methods=['GET', 'POST', 'PUT'])
def welcome_battery_button():
    """
    Returns the html power button.
    """
    on_battery, percentage = welcome_battery()['on_battery'], welcome_battery()['percentage']
    if on_battery:
        power_button = '<button id="powerbutton hx-get="/welcome/battery/button" hx-trigger="load, every 1s" hx-target="#powerbutton" class="button is-dark"> <span style="color: #ffa45c;"> <i class="fa fa-warning" aria-hidden="true"></i></span> &nbsp; Power: Battery: ' + percentage + '%</button>'
    else:
        power_button = """<button id="powerbutton hx-get="/welcome/battery/button" hx-trigger="load, every 1s" hx-target="#powerbutton" class="button is-dark"> <span style="color: #a0ff98;"> <i class="fa fa-check" aria-hidden="true"></i></span> &nbsp;""" +  string_dict["power_text"] + "</button>"""
    return str(power_button)


@bp.route('/welcome/internet', methods=['GET'])
def has_internet():
    """
    Very rudimentary internet check.

    Check if we can resolve deb.debian.org.
    """
    try:
        socket.getaddrinfo("deb.debian.org", 80, proto=socket.IPPROTO_TCP)
        canhas = True
    except socket.gaierror:
        canhas = False
    return canhas


@bp.route('/welcome/internet/button', methods=['GET'])
def welcome_internet_button():
    """
    Draw updated button depending on internet status.
    """
    if has_internet():
        return('&nbsp; <button id="internetbutton" class="button is-dark" hx-get="/welcome/internet/button" hx-trigger="load, every 1s" hx-target="#internetbutton"><span style="color: #a0ff98;"> <i class="fa fa-check" aria-hidden="true"></i></span> &nbsp; Internet </button>')
    else:
        return('&nbsp; <button id="internetbutton" class="button is-dark" hx-get="/welcome/internet/button" hx-trigger="load, every 1s" hx-target="#internetbutton"><span style="color: #ffa45c;"> <i class="fa fa-warning" aria-hidden="true"></i></span> &nbsp; Internet </button>')


def build_stringlist():
    """
    Return all the strings that is used in this applet."
    """
    string_dict = {}
    string_dict['menu_item'] = _("Welcome")
    # In the future, these will be loaded from their own modules
    string_dict['menu_item_users'] = _("Users")
    string_dict['menu_item_disks'] = _("Disks")
    string_dict['menu_item_software'] = _("Software")
    string_dict['menu_item_summary'] = _("Summary")
    string_dict['welcome_text'] = _("Welcome! This setup program will install Debian on to your system.")
    string_dict['confirm_text'] = _("Please confirm the following details:")
    string_dict['language_text'] = _("Language:")
    string_dict['keylayout_text'] = _("Keyboard Layout:")
    string_dict['timezone_text'] = _("Time Zone:")
    string_dict['basicsettings_text'] = _("Basic Settings:")
    string_dict['power_text'] = _("Power")
    string_dict['internet_text'] = _("Internet")
    string_dict['next_text'] = _("Next")
    string_dict['back_text'] = _("Back")
    lang_dict = {}
    lang_dict['af'] = _("Afrikaans")
    lang_dict['en'] = _("English (International)")
    lang_dict['en-us'] = _("English (United States)")
    lang_dict['en-uk'] = _("English (United Kingdom)")
    lang_dict['en-za'] = _("English (South Africa)")
    string_dict['lang_list'] = lang_dict
    return string_dict


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

    #TODO: temporary hack: We need an automated way to translate all menu items
    current_app.config['CONFIG']['settings']['menu']['users'] = (build_stringlist()['menu_item_users'], "/users", 20)
    current_app.config['CONFIG']['settings']['menu']['disks'] = (build_stringlist()['menu_item_disks'], "/disks", 30)
    current_app.config['CONFIG']['settings']['menu']['software'] = (build_stringlist()['menu_item_software'], "/software", 40)
    current_app.config['CONFIG']['settings']['menu']['summary'] = (build_stringlist()['menu_item_summary'], "/summary", 50)


def build_summary():
    """
    Write up a summary of what this module will do.
    """
    html = ("<b><big>Basic settings</big></b><p> Language: " + lang + "</p>")
    if not 'Summary' in current_app.config['CONFIG']:
        current_app.config['CONFIG']['Summary'] = {}
    current_app.config['CONFIG']['Summary']['welcome'] = {}
    current_app.config['CONFIG']['Summary']['welcome']['heading'] = "Basic Settings"
    print(current_app.config['CONFIG']['Summary']['welcome'])
    text = "Language: " + str(current_app.config['CONFIG']['settings']['language'])
    current_app.config['CONFIG']['Summary']['welcome']['text'] = text
    return(html)


set_language(current_app.config['CONFIG']['settings']['language'])
build_menu
