from aiohttp import web, hdrs


async def get_vid_pid_from_request(request):
    try:
        printer_id = request.query.get('printer_id', request.query.get('printer_id_string'))
        if not printer_id:
            if request.content_type == 'application/json':
                request_args = await request.json()
            elif request.method == hdrs.METH_POST:
                request_args = await request.post()
            else:
                return None, None
            if isinstance(request_args, dict):
                if 'VID' in request_args and 'PID' in request_args:
                    vid = request_args['VID']
                    pid = request_args['PID']
                else:
                    printer_id = request_args.get('printer_id_string', request_args.get('printer_id'))
        if printer_id:
            for sep in ("_", ":"):
                if printer_id.count(sep) == 2:
                    break
            else:
                raise ValueError
            vid, pid = printer_id.split(sep, 2)[:2]
        else:
            raise ValueError
    except (ValueError, TypeError, OSError) as e:
        raise web.HTTPBadRequest(text='No not bad printer id: ' + str(e))
    return vid, pid


async def get_printer_types(request):
    vid, pid = await get_vid_pid_from_request(request)
    filter_list = [vid, pid]
    filter_dict = {'VID': vid, 'PID': pid}
    printer_types = []
    for profile in request.app['3dp_app'].user_login.profiles:
        if not vid or not pid or filter_list in profile.get('vids_pids', []):
            printer_types.append({'alias': profile['alias'], 'name': profile['name']})
        for connection in profile.get('v2', {}).get('connections', []):
            if filter_dict in connection.get('ids'):
                printer_types.append({'alias': profile['alias'], 'name': profile['name'], 'conn_id': connection.get('id'), 'conn_type': connection.get('type'), 'conn_name': connection.get('name')})
    return web.json_response(printer_types)


async def get_printer_profiles(request):
    vid, pid = await get_vid_pid_from_request(request)
    profiles = request.app['3dp_app'].user_login.profiles
    if not vid or not pid:
        printer_profiles = profiles
    else:
        filter_list = [vid, pid]
        filter_dict = {'VID': vid, 'PID': pid}
        printer_profiles = []
        for profile in profiles:
            if filter_list in profile.get('vids_pids', []):
                printer_profiles.append(profile)
            else:
                for connection in profile.get('v2', {}).get('connections', []):
                    if filter_dict in connection.get('ids'):
                        printer_profiles.append(profile)
    return web.json_response(printer_profiles)
