package lrs.visitor;
import lrs.*;
import java.util.*;

public class InsertInOrder<T> implements IAlgo {
    
    private Comparator<T> _order;
    
    public InsertInOrder(Comparator<T> ord) {
        _order = ord;
    }
    
    /**
     * Simply inserts the given parameter n at the front.
     * @param host an empty LRStruct.
     * @param n an Object to be inserted in order into host,
     *   based on the given Comparator.
     * @return LRStruct
     */
    public Object emptyCase(LRStruct host, Object... n) {
        return host.insertFront(n[0]);
    }
    
    /**
     * Based on the comparison between first and n,
     * inserts at the front or recurs!
     * @param host a non-empty LRStruct.
     * @param n an Object to be inserted in order into host,
     *   based on the given Comparator.
     * @return LRStruct
     */
    public Object nonEmptyCase(LRStruct host, Object... n) {
        if (_order.compare( (T) n[0], (T) host.getFirst()) < 0) {
            return host.insertFront(n[0]);
        }
        else {
            return host.getRest().execute(this, n);
        }
    }
}

