package ifs.example.jobshop;

import ifs.model.*;
import java.util.*;

/**
 * Machine constraint.
 * <br><br>
 * Each machine contians a given set of operations (variables).
 * A machine constraint is satisfied, if all operations on it do not overlap in time.
 *
 * @author <a href="mailto:muller@ktiml.mff.cuni.cz">Tomas Muller</a>
 * @version 1.0
 */
public class Machine extends Constraint {
    private int iMachineNumber = -1;
    
    /**
     * Constructor 
     * @param machineNumber machine number
     */
    public Machine(int machineNumber) {
        super();
        iMachineNumber = machineNumber;
    }
    
    /** Get machine number */
    public int getMachineNumber() { return iMachineNumber; }
    
    
    /**
     * Adds conflicting operations into the set of conflicts.
     */
    public void computeConflicts(Value value, java.util.Set conflicts) {
        Location location = (Location)value;
        Operation operation = (Operation)value.variable();
        for (Enumeration e=assignedVariables().elements();e.hasMoreElements();) {
            Operation o = (Operation)e.nextElement();
            if (o.getOperationNumber()==operation.getOperationNumber() && o.getJobNumber()==operation.getJobNumber()) continue;
            Location l = (Location)o.getAssignment();
            if (l.overlap(location)) conflicts.add(l);
        }
    }
    
    /**
     * True if there is an operation from the machine which violates with the given assignment.
     */
    public boolean inConflict(Value value) {
        Location location = (Location)value;
        Operation operation = (Operation)value.variable();
        for (Enumeration e=assignedVariables().elements();e.hasMoreElements();) {
            Operation o = (Operation)e.nextElement();
            if (o.getOperationNumber()==operation.getOperationNumber() && o.getJobNumber()==operation.getJobNumber()) continue;
            Location l = (Location)o.getAssignment();
            if (l.overlap(location)) return true;
        }
        return false;
    }
    
    /**
     * True if the two assignments (placement of opeartions of the machine in time) violates each other.
     */
    public boolean isConsistent(Value value1, Value value2) {
        return !((Location)value1).overlap((Location)value2);
    }
    
    /** string representation -- for debuging and printing purposes */
    public String toString() { return getName(); }
    
   /**
     * Name of the machine (e.g. M10 where 10 is the machine number)
     */
     public String getName() { return "M"+iMachineNumber; }
}
