from aiohttp import web, hdrs


def get_network_detector(request):
    app = request.app['3dp_app']
    network_detector = app.detectors.get('NetworkDetector')
    if not network_detector:
        raise web.HTTPInternalServerError(text='NetworkDetector disabled')
    return network_detector

async def network_printers(request):
    network_detector = get_network_detector(request)
    return web.json_response(network_detector.get_printers_list())

async def remember_network_printer(request):
    if request.content_type == 'application/json':
        post_data = await request.json()
    else:
        post_data = await request.post()
    printer_ip = post_data.get('printer_ip')
    printer_port = post_data.get('printer_port')
    printer_type = post_data.get('printer_type')
    run_detector = post_data.get('run_detector', False)
    password = post_data.get('password', '')
    serial_number = post_data.get('serial_number', post_data.get('forced_SNR', ''))
    run_detector = bool(not serial_number and run_detector == 'on')
    try:
        printer_port = int(printer_port)
    except (TypeError, ValueError):
        printer_port = None
    network_detector = get_network_detector(request)
    if not printer_type:
        raise web.HTTPBadRequest(text="Error: empty printer type")
    if not printer_ip:
        raise web.HTTPBadRequest(text="Error: empty printer ip")
    network_detector.remember_printer(printer_type, printer_ip, printer_port, None, None, serial_number, password, run_detector)
    return web.HTTPOk()

async def forget_network_printer(request):
    if request.content_type == 'application/json':
        post_data = await request.json()
        printer_id = post_data.get('printer_id')
    elif request.method == hdrs.METH_POST:
        post_data = await request.post()
        printer_id = post_data.get('printer_id')
    else:
        printer_id = request.query.get('printer_id')
    if not printer_id:
        printer_id = request.match_info.get('printer_id')
    if not printer_id:
        return web.HTTPBadRequest(text='No printer id. Could be string or json_dict or form dict')
    network_detector = get_network_detector(request)
    if isinstance(printer_id, str):
        try: 
            vid, pid, snr = printer_id.split('_', 2)
        except ValueError:
            raise web.HTTPBadRequest(text='Invalid printer id: ' + printer_id)
        printer_id = {'VID': vid, 'PID': pid, 'SNR': snr}
    if network_detector.forget_printer(printer_id):
        return web.HTTPOk()
    return web.HTTPNotFound(text=f'No printer with id {printer_id} to forget')
