from aiohttp import web
from aiohttp import hdrs

import config
from web_interface.auth import check_auth


def get_button_text(enabled, name):
    if enabled:
        default_first_word = "Disable" 
    else:
        default_first_word = "Enable"
    if name == 'gpio_interface':
        text = default_first_word + 'GPIO interface'
    elif name == 'backward_compatible_serials':
        if enabled:
            text = 'Switch to new style SNR'
        else:
            text = 'Switch to old style SNR'
    else:
        text = default_first_word + " " + name.replace("_", " ")
    return text


def button_state(app, name, toggle=False):
    enabled = None
    if name == 'virtual_printer':
        if toggle:
            app.toggle_virtual_printer()
        enabled = app.virtual_printer_enabled
    elif name == 'gpio_interface':
        gpio_interface = getattr(app, 'gpio_interface')
        if gpio_interface:
            enabled = gpio_interface.enabled
        else:
            enabled = False
        if toggle:
            app.settings['gpio_interface']['enabled'] = not enabled
    elif name in app.settings:
       if type(app.settings[name]) == bool:
           enabled = not app.settings[name]
           if toggle:
               app.settings[name] = enabled 
       elif 'enabled' in app.settings[name]:
           enabled = not app.settings[name]['enabled']
           app.settings[name]['enabled'] = enabled
       config.Config.instance().save_settings(app.settings)
    return enabled


async def toggle_button(request):
    check_auth(request)
    app = request.app['3dp_app']
    print('Button match info:' + request.match_info.get('button', ''))
    button_name = request.match_info.get('button', '').strip('/').split('/')[0]
    if not button_name:
        raise web.HTTPNotFound()
    state = button_state(app, button_name, request.method == hdrs.METH_POST)
    if state is None:
        raise web.HTTPNotFound()
    if request.path.endswith('json'):
        return web.json_response(data = state) 
    return web.Response(body=get_button_text(state, button_name), content_type='text/plain')
