import logging

from aiohttp import web, hdrs

import rights
import platforms
from web_interface.auth import check_auth


async def wifi_ap_leases(request):
    check_auth(request)
    detector = request.app['3dp_app'].detectors['DNSMasqDetector']
    if request.method == hdrs.METH_DELETE:
        if request.content_type == 'application/json':
            post_data = await request.json()
        else:
            post_data = await request.post()
        ip = post_data.get('ip')
        if not ip:
            ip = request.query.get('ip')
        if not ip:
            raise web.HTTPBadRequest(text='No ip field in delete request')
        detector.forget_printer(ip)
    leases_list = detector.get_printers_list()
    return web.json_response(data=leases_list)


async def wifi_ap_settings(request, enable=None, redirect=None):
    check_auth(request)
    logger = logging.getLogger('wifi_ap_handler')
    if request.method == hdrs.METH_POST:
        if request.content_type == 'application/json':
            post_data = await request.json()
        else:
            post_data = await request.post()
        logger.debug('WiFi access point args: ' + str(post_data))
        logger.info('WiFi access point set enable to: ' + str(post_data))
        rights.write_wifi_ap_creds(post_data)
        if enable is None:
            if 'enabled' in post_data:
                enable = post_data['enabled']
            else:
                enable = request.query.get('enabled')
            if enable == 'on' or enable is True or enable == 1:
                enable = True
            else:
                enable = False
        if enable is None:
            pass
        elif enable:
            rights.enable_wifi_ap()
        else:
            rights.disable_wifi_ap()
    if redirect:
        raise web.HTTPFound(redirect)
    resp_json = rights.read_wifi_ap_creds()
    resp_json['enabled'] = rights.is_wifi_ap_running()
    resp_json['installed'] = rights.is_wifi_ap_installed()
    resp_json['installable'] = rights.is_wifi_ap_installable()
    return web.json_response(data=resp_json)


async def wifi_ap_settings_with_redirect(request):
    if platforms.PLATFORM == 'rpi':
        return await wifi_ap_settings(request, redirect='/pages/wifi_access_point')
    else:
        return await wifi_ap_settings(request, redirect='/manage_settings')


async def wifi_ap_switch(request):
    check_auth(request)
    if request.path == '/wifi_ap_enable':
        enable = True
    elif request.path == '/wifi_ap_disable':
        enable = False
    else:
        enable = None
    return await wifi_ap_settings(request, enable=enable)
