package flexa.ff;

import flexa.fb.*;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;


public class table extends FComponent {
    
    
    public table() {
        super("ff.table");
    }

	public void updateFromRequest(HashMap<String, Object> aParameters) {
	    //if( aParameters.containsKey(this.getValue("name")) )
        //    this.setValue("value", aParameters.get(this.getValue("name")).toString());
	}  
	
	public void event(String aAction, FContext aContext) throws Exception {
	    //Log.getInstance().info("TABLE " + this.name + " event " + aAction);
	    if( this.status == 0 
	        && (hasValue("datasource_oql") || hasValue("datasource_sql"))
	        && (aAction.equals(this.name + ".select") || aAction.equals(this.name + ".refresh") || aAction.equals("start") || aAction.equals("onopen")) 
	        ) {
	        
	        // EXECUTES SQL/OQL
	        Log.info("refresh table " + this.id + " processing datasource");
	        //Log.info(aContext.toString());
	        FResult result = this.processDatasource(aContext);
            int totalrows = result.size();
            FComponent tbody = this.findChildOfType("tr", "type", "body");
            if( tbody == null ) tbody = this.findChildOfType("tr", "type", "");         // @todo more than one row
            FComponent theadergroup = this.findChildOfType("tr", "type", "headergroup");// @todo more than one row
            FComponent tfootergroup = this.findChildOfType("tr", "type", "footergroup");   // @todo more than one row
            String tgroupby = (String)getValue("groupby");
            
            // If no rows, build TRs & TDs from result
            if( tbody == null ) {
                buildRowsFromResult(result);
                return;
                //throw new Exception("No TR body found on table " + (String)getValue("name"));   // @todo armar filas con FResult
            }
            
            // Clone TRs from result
            int tposition = this.getChildren().indexOf(tbody) + 1;
            FComponent torender = tbody;
            FComponent torender2 = null;
            String tid = (String)torender.getValue("id");
            // Por cada registro clona elemento
            Object tlastgroupby = null;
            int tgroupid = 0;
            FRow row = null;
            FRow lastrow = null;
            for(int i = 0; i < totalrows; i++) {
                row = result.get(i);
                Log.getInstance().info("TR body ds row " + i);
                //Log.getInstance().info(row.toString());
                    
                // Group by header/footer
                if( tgroupby != null ) {
                    this.context = new FContext(row);
                    Object tgroupbyval = this.calcExpression(aContext, "groupby");
                    if( i == 0 ) theadergroup.context = new FContext(row);
                    if( i > 0 && !tgroupbyval.equals(tlastgroupby) ) {
                        tgroupid++;
                        // Footer group
                        // Clone footer
                        torender2 = (FComponent)tfootergroup.clone();
                        torender2.setValue("id", tfootergroup.getValue("id") + "[" + tgroupid + "]");
                        torender2.context = new FContext(lastrow);
                        this.addChild(torender2, tposition );
                        tposition++;

                        // Header group
                        Log.info("Changed group by i" + i + " " + tgroupbyval);
                        torender2 = (FComponent)theadergroup.clone();
                        //tlastgroupby
                        torender2.setValue("id", theadergroup.getValue("id") + "[" + tgroupid + "]");
                        torender2.context = new FContext(row);
                        this.addChild(torender2, tposition );
                        tposition++;
                    }
                    tlastgroupby = tgroupbyval;
                }
                
                
                if( i > 0 ) {
                    // Clone and add to father
                    //torender = (FComponent)PipedDeepCopy.copy(this);
                    torender = (FComponent)tbody.clone();
                    //torender = new FComponent(this);
                    torender.setValue("id", tid + "[" + i + "]");
                    this.addChild(torender, tposition);
                    tposition++;
                }
                //Log.info("Row moredata:");
                //Log.info(row.toString());
                //Log.info(((FObject)row.get("x")).info());
                //torender.moreData = row;
                torender.context = new FContext(row);
                //Log.getInstance().info("Torender " + torender.getValue("id"));
                lastrow = row;
            }
            // Footer group
            if( totalrows > 0 && tgroupby != null ) {
                tfootergroup.context = new FContext(row);
            }
            

            //Log.getInstance().info("TABLE EVENT end: " + torender.info());
            // @todo eliminar clonados demas de anteriores clonaciones
            // @todo si no hay registros limpiar elemento y ponerlo como inactivo (status -1)
	    }
	    super.event(aAction, aContext);
	}
	

    public void buildRowsFromResult(FResult result) throws Exception {
        // 
        Log.info("ff:table buildRowsFromResult");
        Log.info("ff:table buildRowsFromResult : " + result);
        int totalrows = result.size();


        //FComponent tbody = this.findChildOfType("tr", "type", "body");
        //@todo buscar one row for body 
        //if( tbody == null ) 
        //if( tbody == null ) throw new Exception("No TR body found on table " + (String)getValue("name"));   // @todo armar filas con FResult
        //int tposition = this.getChildren().indexOf(tbody);
        //FComponent torender = tbody;
        //String tid = (String)torender.getValue("id");
        // Por cada registro genera TR
        tr torender = null;
        String tid = "";
        this.clearChildren();
        for(int i = 0; i < totalrows; i++) {
            FRow row = result.get(i);
            Log.getInstance().info("TR from row " + i);
            // Header  @todo with resulmeta for empty results
            if( i == 0 ) { 
                tr trheader = new tr();
                trheader.setValue("id", this.id + "_header");
                trheader.setValue("name", this.id + "_header");
                trheader.setValue("type", "header");
                trheader.buildHeaderFromFRow(row);
                this.addChild(trheader);
            }
            
            // Clone and add to father
            torender = new tr();
            tid = this.id + "[" + i + "]";
            torender.setValue("id", tid);
            torender.setValue("name", tid);
            torender.setValue("type", "body");
            torender.buildFromFRow(row);
            this.addChild(torender);
            //torender.setValue("id", tid + "[" + i + "]");
        }

    }
    
	public Object call(FContextInterface context, String name, Object... args) throws Exception {
		switch(name) {
		    case "buildRowsFromResult":
		        buildRowsFromResult((FResult)args[0]);
		        break;

		}
		return null;
	}
    

}