from aiohttp import web

import web_interface.printers_html
import web_interface.auth


def get_printers(app):
    printers = []
    for printer_interface in app.printer_interfaces:
        status_report = printer_interface.status_report()
        try:
            name = printer_interface.printer_profile['name']
        except (AttributeError, TypeError, KeyError):
            name = printer_interface.id_string
        printers.append({'name': name,
                         'status_report': status_report,
                         'temps': web_interface.printers_html.get_printer_temps_string(status_report),
                         'error': web_interface.printers_html.get_printer_error_string(printer_interface)})
    return printers


def get_confirm_identical_printers(app):
    usb_info_list = []
    for printer_interface in app.printer_interfaces:
        usb_info_list.append(printer_interface.id_string)
    for usb_info in usb_info_list:
        if usb_info_list.count(usb_info) > 1:
            return True
    return False


async def tray(request):
    if not web_interface.auth.request_is_from_localhost(request):
        raise web.HTTPForbidden(text='Error: tray requests allowed only from a localhost')
    status = 200
    app = request.app['3dp_app']
    path = request.match_info.get('path')
    if path == 'get_active_printers':
        response = get_printers(app)
    elif path == 'confirm_identical_printers':
        response = get_confirm_identical_printers(app)
    elif path == 'updates_available':
        response = getattr(getattr(app, 'updater', None), 'updates_available', False)
    else:
        response = '{}'
        status = 404
    return web.json_response(data=response, status=status)
