def create_device_group():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    check_json(request)
    name = get_json(request).get('name')
    desc = get_json(request).get('description')
    customer = get_json(request).get('customer')

    if desc is None:
        desc = ''

    empty_check(name, error_message='Name cannot be empty')

    DccaDeviceGroup.is_name_taken(name, ctx.current_user)

    group = DccaDeviceGroup(name, description=desc, customer=customer)
    try:
        session.add(group)
        session.commit()
    except Exception:
        raise DCCAException('Fail to create device group')

    results = OrderedDict()
    results['status'] = 'success'
    results['message'] = 'Success to create a group'
    results['group'] = group.as_dict(schema=DeviceGroupSchema)

    return jsonify(results)
def device_save_to_group():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    limit = request.args.get('limit') if request.args.get(
        'limit') else DEFAULT_GROUP_LIMTI
    offset = request.args.get('offset') if request.args.get(
        'offset') else DEFAULT_GROUP_OFFSET

    check_json(request)
    group_name = get_json(request).get("name")
    group_desc = get_json(request).get('description')
    customer_id = get_json(request).get('customer')
    bind_fail_list = []
    bind_list = []

    if group_desc is None:
        group_desc = ''

    customer = DccaCustomer.get_by_id(customer_id)
    if customer is None:
        customer_id = None
        session.commit()

    empty_check(group_name, error_message='Name cannot be empty')

    DccaDeviceGroup.is_name_taken(group_name, ctx.current_user)

    group = DccaDeviceGroup(group_name,
                            description=group_desc,
                            customer=customer_id)
    try:
        session.add(group)
    except Exception:
        raise DCCAException("Fail to create device group")
    devices = get_json(request).get('devices')

    if devices:
        for device in devices:
            device = Host.get_by_id(device)
            if device is None:
                bind_fail_dict = {
                    'id': device,
                    'message': 'The device_id does not exist'
                }
                bind_fail_list.append(bind_fail_dict)
            else:
                if not device.has_group(group):
                    try:
                        device.groups.append(group)
                        session.add(device)
                        session.commit()
                        bind_list.append(device)
                    except Exception as e:
                        bind_fail_dict = {'id': device.id, 'message': e}
                        bind_fail_list.append(bind_fail_dict)
                        raise DCCAException('Fail to bind device to group')
                else:
                    message = 'This device already exists in the {} group, please do not add it repeatedly'.format(
                        group.name)
                    bind_fail_dict = {'id': device.id, 'message': message}
                    bind_fail_list.append(bind_fail_dict)
    else:
        intersection = get_json(request).get('intersection', False)

        results = []
        condition_items = get_json(request).get('by_condition')
        if 'by_condition' in get_json(request) and condition_items:
            if not any([x['value'] for x in condition_items]):
                devices_by_attr = set()
            else:
                devices_by_attr = device_attr_filter(request.cursor, uid,
                                                     limit, offset,
                                                     condition_items)
                results.append(devices_by_attr)
        else:
            devices_by_attr = set()

        if 'by_solution' in get_json(request) and get_json(request).get(
                'by_solution'):
            solution_id = get_json(request).get('by_solution')

            devices_by_sol = device_solution_filter(request.cursor, uid, limit,
                                                    offset, solution_id)
            results.append(devices_by_sol)

        else:
            devices_by_sol = set()

        if intersection:
            if results:
                devices = list(reduce(lambda x, y: x & y, results))
            else:
                devices = []
        else:
            devices = list(devices_by_attr | devices_by_sol)

        if len(devices) == 0:
            return jsonify({
                "status":
                "fail",
                "message":
                "The device that matches the search criteria is empty. Please re-enter."
            })

        for device in devices:
            device = Host.get_by_id(device['id'])
            if device is None:
                bind_fail_dict = {
                    'id': device.id,
                    'message': 'The device_id does not exist'
                }
                bind_fail_list.append(bind_fail_dict)
            else:
                if not device.has_group(group):
                    try:
                        device.groups.append(group)
                        session.add(device)
                        session.commit()
                        bind_list.append(device)
                    except Exception as e:
                        bind_fail_dict = {'id': device.id, 'message': e}
                        bind_fail_list.append(bind_fail_dict)
                        raise DCCAException('Fail to bind device to group')
                else:
                    message = 'This device already exists in the {} group, please do not add it repeatedly'.format(
                        group.name)
                    bind_fail_dict = {'id': device.id, 'message': message}
                    bind_fail_list.append(bind_fail_dict)

    results = OrderedDict()
    if len(bind_list) == 0:
        results['status'] = "fail"
        results['message'] = "Fail to bind device to group"
        results['group'] = group.as_dict(schema=DeviceGroupBindSchema)
        results['devices'] = {}
    else:
        results['status'] = "success"
        results['message'] = "Success to add device to group"
        results['group'] = group.as_dict(schema=DeviceGroupBindSchema)
        results['devices'] = {}
        results['devices']['success'] = []
        results['devices']['success_total'] = len(bind_list)
        for device in bind_list:
            results['devices']['success'].append(
                device.as_dict(schema=DeviceIDSchema))
    results['devices']['fail'] = []
    results['devices']['fail_total'] = len(bind_fail_list)
    for device_fail in bind_fail_list:
        results['devices']['fail'].append(device_fail)

    return jsonify(results)