from aiohttp import web


async def get_vid_pid_from_request(request):
    try:
        request_args = await request.json()
        printer_id_string = request_args.get('printer_id_string') 
        if printer_id_string:
            filter_vid = request_args[:4]
            filter_pid = request_args[4:8]
            filter_list = [filter_vid, filter_pid]
            filter_dict = {'VID': filter_vid, 'PID': filter_pid}
        elif type(request_args) == dict and 'VID' in request_args and 'PID' in request_args:
            filter_vid = request_args.get('VID')
            filter_pid = request_args.get('PID')
            filter_list = [filter_vid, filter_pid]
            filter_dict = {'VID': filter_vid, 'PID': filter_pid}
        else:
            raise ValueError
    except (ValueError, TypeError, OSError):
        filter_vid, filter_pid, filter_list, filter_dict = None, None, None, None
    return filter_vid, filter_pid, filter_list, filter_dict


async def get_printer_types(request):
    filter_vid, filter_pid, filter_list, filter_dict = await get_vid_pid_from_request(request)
    printer_types = []
    for profile in request.app['3dp_app'].user_login.profiles:
        if not filter_vid or not filter_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):
    filter_vid, filter_pid, filter_list, filter_dict = await get_vid_pid_from_request(request)
    profiles = request.app['3dp_app'].user_login.profiles
    if not filter_dict:
        printer_profiles = profiles
    else:
        printer_profiles = []
        for profile in request.app['3dp_app'].user_login.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)
