from siege.util import Random, WeightedRandomGenerator

def createEquipment(minAttributes, maxAttributes, fixed):
    def createEquipmentInner(entity, component):
        assignMaxAttributes(component, minAttributes, maxAttributes)
        component.maxAttributes += len(fixed)
        for attribute in fixed:
            component.addAttribute(attribute(component))
        addPotentials(component)
    return createEquipmentInner


def assignMaxAttributes(component, minimum, maximum):
    component.maxAttributes = minimum
    quality = component.quality
    while maximum > component.maxAttributes:
        chance = Random.get(40, 80)
        if quality < chance:
            break
        quality -= chance
        component.maxAttributes += 1


def addPotentials(component, count=-1):
    #Add attributes to the EquipmentComponent
    if not component.potentials:
        return
    if count == -1:
        #If count is undefined then calculate it
        availableSlots = component.maxAttributes - len(component.getAttributes())
        if not availableSlots:
            return
        elif availableSlots == 1:
            count = 1
        else:
            weights = []
            start = availableSlots / 2
            weight = 2
            diff = availableSlots - start
            for x in xrange(diff):
                weight = int(weight * (Random.getFloat() + 1.0))
                weights.append(weight)
            count = start + (diff - WeightedRandomGenerator(weights)())
    potentials = []
    weights = []
    for potential in component.potentials:
        if component.quality >= potential.quality:
            potentials.append(potential)
            weights.append(potential.weight)
    while count and component.potentials:
        index = WeightedRandomGenerator(weights)()
        potential = potentials[index]
        attribute = potential.onCreate(component)
        component.addAttribute(attribute)
        #Remove this potential from the list
        index = 0
        for p in component.potentials:
            if p.onCreate == potential.onCreate:
                del component.potentials[index]
                break
            index += 1
        del potentials[index]
        del weights[index]
        count -= 1
