def apply(self, basket, condition, offer):
    if isinstance(condition, ValueCondition):
        return ZERO_DISCOUNT
    line_tuples = self.get_applicable_lines(offer, basket, range=condition.range)
    if (not line_tuples):
        return ZERO_DISCOUNT
    num_permitted = int(condition.value)
    num_affected = 0
    value_affected = D('0.00')
    covered_lines = []
    for (price, line) in line_tuples:
        if isinstance(condition, CoverageCondition):
            quantity_affected = 1
        else:
            quantity_affected = min(line.quantity_without_offer_discount(offer), (num_permitted - num_affected))
        num_affected += quantity_affected
        value_affected += (quantity_affected * price)
        covered_lines.append((price, line, quantity_affected))
        if (num_affected >= num_permitted):
            break
    discount = max((value_affected - self.value), D('0.00'))
    if (not discount):
        return ZERO_DISCOUNT
    discount_applied = D('0.00')
    last_line = covered_lines[(- 1)][1]
    for (price, line, quantity) in covered_lines:
        if (line == last_line):
            line_discount = (discount - discount_applied)
        else:
            line_discount = self.round(((discount * (price * quantity)) / value_affected))
        apply_discount(line, line_discount, quantity, offer)
        discount_applied += line_discount
    return BasketDiscount(discount)
def apply(self, basket, condition, offer):
    if isinstance(condition, ValueCondition):
        return ZERO_DISCOUNT
    line_tuples = self.get_applicable_lines(offer, basket, range=condition.range)
    if (not line_tuples):
        return ZERO_DISCOUNT
    num_permitted = int(condition.value)
    num_affected = 0
    value_affected = D('0.00')
    covered_lines = []
    for (price, line) in line_tuples:
        if isinstance(condition, CoverageCondition):
            quantity_affected = 1
        else:
            quantity_affected = min(line.quantity_without_offer_discount(offer), (num_permitted - num_affected))
        num_affected += quantity_affected
        value_affected += (quantity_affected * price)
        covered_lines.append((price, line, quantity_affected))
        if (num_affected >= num_permitted):
            break
    discount = max((value_affected - self.value), D('0.00'))
    if (not discount):
        return ZERO_DISCOUNT
    discount_applied = D('0.00')
    last_line = covered_lines[(- 1)][1]
    for (price, line, quantity) in covered_lines:
        if (line == last_line):
            line_discount = (discount - discount_applied)
        else:
            line_discount = self.round(((discount * (price * quantity)) / value_affected))
        apply_discount(line, line_discount, quantity, offer)
        discount_applied += line_discount
    return BasketDiscount(discount)