/*
 * FormatCommandJoinRight.java
 *
 * Created on 9 mei 2005, 21:36
 */

package it.businesslogic.ireport.gui.command;

import it.businesslogic.ireport.Band;
import it.businesslogic.ireport.OperationType;
import it.businesslogic.ireport.ReportElement;

import java.awt.Point;
import java.awt.Rectangle;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

/**
 *
 *
 */
public class FormatCommandJoinRight extends FormatCommand {
    int actual_x;
    
    {
        operationType = OperationType.JOIN_RIGHT;
    }
    
    public void executeDeeper() {
        // 1 Check which bands to treat:
        Vector used_bands = new Vector();
        
        for (Iterator h = jrf.getSelectedElements().iterator(); h.hasNext(); ) {
            ReportElement bandRe = (ReportElement) h.next();

            if (!used_bands.contains(bandRe.getBand())) {
                used_bands.add( bandRe.getBand());
                mf.logOnConsole("\nNext band: " + bandRe.getBand().toString() + "\n" );
            } else {
                continue;
            }
            
            //Band b = (Band)bands_enum.nextElement();
            Band b = bandRe.getBand();
            
            Vector myElements = new Vector();
            Enumeration enum2 = jrf.getSelectedElements().elements();
            
            while (enum2.hasMoreElements()) {
                ReportElement re = (ReportElement)enum2.nextElement();
                mf.logOnConsole("\n" + re.toString() + "\n" );
                if (re.getBand() == b) {
                    // insert this element in the right position...
                    mf.logOnConsole( "if (re.getBand == b) \n" );
                    if (myElements.size() == 0) {
                        myElements.add(re);
                    } else {
                        boolean inserted=false;
                        for (int i=0; i<myElements.size(); ++i) {
                            ReportElement re2 = (ReportElement)myElements.elementAt(i);
                            if (re.getPosition().x > re2.getPosition().x) {
                                myElements.insertElementAt(re, i);
                                inserted = true;
                                break;
                            }
                        }
                        if (!inserted){
                            myElements.addElement(re);
                        }
                        
                    }
                }
            }
            
            // Repositioning elements...
            ReportElement re = (ReportElement) myElements.elementAt(0);
            actual_x = re.getPosition().x + re.getWidth();
            
            // use myELements instead of jrf.getElements()
            processElements( myElements.elements() );
        }
    }
    
    public void modify() {
        
        re.setPosition( new Point(actual_x - re.getWidth(), re.getPosition().y) );
        actual_x -= re.getWidth();
    }
    
}
