// generated by FBuilder
package flexa.ff;
import flexa.fb.*;
import java.util.Map;
import java.util.HashMap;
import javax.script.*;
import java.util.ArrayList;
public class form extends FComponent {
    //
    // CONSTRUCTOR
    //
    public form() {
        super("ff.form");
    }
    
    // 
    // Methods
    //
    
    
    public void updateFromRequest(HashMap<String, Object> aParameters)  throws Exception { 
    		super.updateFromRequest(aParameters); 
		//if( aParameters.containsKey(this.getValue("name")) ) 
		//   this.setValue("value", aParameters.get(this.getValue("name")).toString()); 
		 
		// @todo update Object

    }
    


    
    public void updateFromObject(FObjectInterface aObject, FContext aContext)  throws Exception { 
    		this.removeClonedChildren(); 
		super.updateFromObject(aObject, aContext);

    }
    


    
    public Object call(FContextInterface contexti, String aname, Object... args)  throws Exception { 
    		ArrayList<FComponent> comps = findDescendantesWithName(aname);
		if( comps.size() > 0 ) 
		    return comps.get(0).call(contexti, aname, args);
		return null;

    }
    


    
    public void setFObject(FObject aobject)  throws Exception { 
    		this.fobject = aobject;
		super.setFObject(aobject);

    }
    


    // 
    // Events
    //
	public void event(String aAction, FContext aContext) throws Exception {
        // Events
        
    
        // onopen EVENT
        if( LibText.stringToArray("onopen,start,refresh,onrefresh").contains(aAction) ) {
        			/**
			// If datasource, instantiates object or list objects
			Log.info("form onopen " + this.name);
			if( getValue("datasource") != null && !((String)getValue("datasource")).equals("") ) {
			    
			    String tModule = (String)aContext.get("_module"); //(String)this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("_module"); 
			    String tName = (String)this.getValue("name");
			    String tds = (String)getValue("datasource");
			    if( aContext.getContext("request_").hasMember("id") ) { 
			        // Instantiates object
			        // Form Mode
			        
			        
			        //this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id") != null ) { 
			        // If request ID not empty 
			        String tsid = aContext.getContext("request_").get("id").toString().trim();  //this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id").toString(); 
			        
			        if( !tsid.equals("") && !tsid.equals("0") ) {  
			            Log.info("form-mode " + tsid);
			            // Load Object (ORM) 
			            this.setValue("formmode", "form-mode");
			            int tId = Integer.parseInt(tsid); // ID of object 
			            Log.getInstance().info("FORM start datasource : " + tds +  " id " + tId);                 
			            Log.getInstance().info("FORM ORMgetobject " + tModule + "." + tName + " id: " + tId + " db " + aContext.db); 
			            this.fobject = ORM.getInstance().getObject( tModule + "." + tName, tId, aContext);  
			            aContext.addContext("obj", this.fobject);  // Expose fobject & its attributes to context 
			            this.updateFromObject(this.fobject, aContext); // Set variables on FFields 
			        } else {
			            Log.info("form-mode-new " + tsid);
			            // New
			            this.setValue("formmode", "form-mode-new");
			            Log.getInstance().info("FORM start datasource : " + tds +  " NEW " + tsid);                 
			            Log.getInstance().info("FORM ORMgetobject " + tModule + "." + tName + " id: " + tsid + " db " + aContext.db); 
			            Log.info("form class", this.fclass);
			            this.fobject = ORM.getInstance().newObject( tModule + "." + tName, aContext, this);
			            aContext.addContext("obj", this.fobject);  // Expose fobject & its attributes to context 
			            this.updateFromObject(this.fobject, aContext); // Set variables on FFields 
			            
			        }
			        
			    } else if( getValue("cansearch") != null && ((String)getValue("cansearch")).equals("yes") ) {
			        // List mode
			        Log.info("list-mode");
			        this.setValue("formmode", "list-mode");
			        
			        // FQuery for list
			        String tsoql = "select x from " + tModule + "." + tName; 
			        FQuery toql = FQuery.parseOql(tsoql);
			        String tsql = toql.generateSql(FQuery.ON_LIST, aContext);
			        //this.setValue("listsql", tsql);
			        
			        Log.info("FORM in list-mode. Generating table with SQL " + tsql);
			   
			        // Build table from result
			        table listtable = (table)this.findChildOfType("table", "id", this.id + "_listtable");
			        if( listtable == null ) {
			            Log.info("Listtable not found, creating");
			            listtable = new table();
			            listtable.setValue("id", this.id + "_listtable");
			            listtable.setValue("name", this.id + "_listtable");
			            listtable.setValue("pagination", "50");
			            listtable.setValue("cansearch", "yes");
			            listtable.setValue("detailwindow", "#" + aContext.get("_module") + "/" + aContext.mainComponent.getName() + "?id=");
			            this.addChild(listtable);
			        }
			        //listtable.setValue("datasource_oql", tsoql);
			        listtable.setValue("datasource_sql", tsql);
			        
			        //listtable.setValue("datasource", tsoql);
			        listtable.event("onopen", aContext);
			        
			        
			        
			    }
			}
			**/

        }
    


    
        // save EVENT
        if( LibText.stringToArray("" + this.name + ".save").contains(aAction) ) {
        			// Save object 
			String tcall;
			Log.getInstance().info("Form save"); 
			// Validate 
			String terrors = this.validate(aContext);
			Log.info("Validate errors:", terrors);
			if( !terrors.equals("") ) {
			    aContext.call(aContext, "error", terrors);
			    return;
			}
			// Beforesave event
			Log.info("ds " + getValue("datasource"));
			//Log.info( aContext.getContext("request_").hasMember("id") ? "hasmember id " : "has not member id");
			Log.info("Executing beforesave. Errors var:", aContext.get("errors"));
			super.event(aAction.replace("save", "beforesave"), aContext);
			Log.info("Executed beforesave. Errors var:", aContext.get("errors"));
			if( aContext.get("errors") != null && aContext.get("errors").toString().trim().length() > 0 ) {
			    return;
			}
			//if( !this.isValid(aContext) ) return;
			// Save
			String tsid = "";
			if( getValue("datasource") != null && !((String)getValue("datasource")).equals("") && aContext.getContext("request_").hasMember("id") ) { // this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id") != null ) { 
			    tsid = aContext.getContext("request_").get("id").toString(); //(String)this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id"); 
			    Log.getInstance().info("Form save id" + tsid); 
			    //if( tsid != null && !tsid.equals("") ) { 
			        // Save object 
			        Log.getInstance().info("Saving form object"); 
			        this.fobject.save(); 
			 
			        // Expose fobject & its attributes to context 
			        //this.fobject.buildScriptBindings(this.engine.getBindings(ScriptContext.ENGINE_SCOPE)); 
			        aContext.addContext("obj", this.fobject); 
			         
			        // Set variables on FFields 
			        this.updateFromObject(this.fobject, aContext); 
			    //} 
			    
			}
			// Onsave event
			super.event(aAction.replace("save", "onsave"), aContext);
			// Cartel guardado
			if( getValue("datasource") != null && !((String)getValue("datasource")).equals("") && aContext.getContext("request_").hasMember("id") ) { // this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id") != null ) { 
			    if( !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "redirect") && !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "closepopup") ) {
			        tcall = "message('Registro guardado')";
			        ((ArrayList)aContext.hash.get("calls")).add(tcall);
			    }
			}
			// Redirect or readonly
			boolean tReadonlymode = this.get("readonlymode") != null && this.get("readonlymode").toString().equals("yes");
			tReadonlymode = false;
			// READONLYMODE
			if( tReadonlymode ) {
			    //this.setValue("formmode", "form-mode form-readonly readonly");
			    if( !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "redirect") && !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "closepopup") ) {
			        if( tsid != null && !tsid.equals("") && !tsid.equals("0") ) {
			            this.setValue("formmode", "form-mode form-readonly readonly");
			        } else {
			            FComponent twin = this.getMainContainer();
			            tcall = "redirect('#" + twin.getCompleteName().replace(".", "/") + "?id=" + this.fobject.getId() + "')";   //window.actualobject._module %>/<%= window.actualobject.name %>?
			            ((ArrayList)aContext.hash.get("calls")).add(tcall);
			        }
			        //tcall = "window.actualview.find('.form-search-btn').click()";
			        //#<%= window.actualobject._module %>/<%= window.actualobject.name %>?
			        
			    }
			// NOT READONLYMODE (redirect to list mode)
			} else {
			    if( getValue("cansearch") != null && ((String)getValue("cansearch")).equals("yes") ) {
			        if( !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "redirect") && !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "closepopup") ) {
			            //tcall = "redirect('#' + window.actualobject._module + '/' + window.actualobject.name + '?')";   //window.actualobject._module %>/<%= window.actualobject.name %>?
			            tcall = "window.actualview.find('.form-search-btn').click()";
			            //#<%= window.actualobject._module %>/<%= window.actualobject.name %>?
			            ((ArrayList)aContext.hash.get("calls")).add(tcall);
			        }
			        
			    }
			}

        }
    


    
        // beforeopen EVENT
        if( LibText.stringToArray("beforeopen").contains(aAction) ) {
        			ArrayList<FComponent> tList = this.findDescendantesWithId("numdoc");
			// If datasource, instantiates object or list objects
			boolean tReadonlymode = this.get("readonlymode") != null && this.get("readonlymode").toString().equals("yes");
			Log.info("form beforeopen " + this.name);
			if( getValue("datasource") != null && !((String)getValue("datasource")).equals("") ) {
			    
			    String tModule = (String)aContext.get("_module"); //(String)this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("_module"); 
			    String tName = (String)this.getValue("name");
			    String tds = (String)getValue("datasource");
			    
			    ///
			    /// FORM MODE
			    ///
			    if( aContext.getContext("request_").hasMember("id") ) { 
			        // Instantiates object
			        // Form Mode
			        
			        
			        //this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id") != null ) { 
			        // If request ID not empty 
			        String tsid = aContext.getContext("request_").get("id").toString().trim();  //this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id").toString(); 
			        
			        // Remove previous subformrows from subforms
			        for( FComponent tsubform : this.findChildsOfType("subform") ) {
			            ((subform)tsubform).removeDescendantsOfType("subformrow");
			        }
			        
			        //
			        //  LOAD MODE
			        // Create or Load object and update this UI with the object
			        if( !tsid.equals("") && !tsid.equals("0") ) {  
			            Log.info("form-mode " + tsid);
			            // Load Object (ORM) 
			            this.setValue("formmode", "form-mode" + (tReadonlymode ? " form-readonly readonly" : ""));
			            int tId = Integer.parseInt(tsid); // ID of object 
			            Log.getInstance().info("FORM start datasource : " + tds +  " id " + tId);                 
			            Log.getInstance().info("FORM ORMgetobject " + tModule + "." + tName + " id: " + tId + " db " + aContext.db); 
			            //this.setFObject(ORM.getInstance().getObject( tModule + "." + tName, tId, aContext));
			            this.setFObject(ORM.getInstance().loadObject( tModule + "." + tName, tId, aContext));
			        //
			        //  NEW MODE
			        } else {
			            Log.info("form-mode-new " + tsid);
			            
			    		if( tList.size() > 0 ) {
			    			Log.info("100NUMDOC val: " + tList.get(0).get("value") + " orig: " +
			    				tList.get(0).getOriginalData("value"));
			    		}
			            
			            
			            // New
			            this.setValue("formmode", "form-mode-new");
			            Log.getInstance().info("FORM start datasource : " + tds +  " NEW " + tsid);                 
			            Log.getInstance().info("FORM ORMgetobject " + tModule + "." + tName + " id: " + tsid + " db " + aContext.db); 
			            Log.info("form class", this.fclass);
			            this.setFObject(ORM.getInstance().newObject( tModule + "." + tName, aContext, this));
			    		if( tList.size() > 0 ) {
			    			Log.info("101NUMDOC val: " + tList.get(0).get("value") + " orig: " +
			    				tList.get(0).getOriginalData("value"));
			    		}
			            this.fobject.updateFromRequest(aContext.getContext("request_"));
			            
			    		if( tList.size() > 0 ) {
			    			Log.info("102NUMDOC val: " + tList.get(0).get("value") + " orig: " +
			    				tList.get(0).getOriginalData("value"));
			    		}
			            
			            String tcall = "focusnext($('.form'))";
			            ((ArrayList)aContext.hash.get("calls")).add(tcall);
			        }
			        this.fobject.setForm(this); // @todo HACERLO LUEGO CUANDO SE EDITE , YA QUE SINO CONFLICTUARÁ CON ALGUIEN QUE ENTRE A VER EL OBJETO
			        aContext.addContext(this.id, this.fobject);     // Expose fobject & its attributes to context    //@commented180724 
			        this.updateFromObject(this.fobject, aContext); // Set variables on FFields 
					if( tList.size() > 0 ) {
						Log.info("103NUMDOC val: " + tList.get(0).get("value") + " orig: " +
							tList.get(0).getOriginalData("value"));
					}
			        
			    ////
			    //// LIST MODE
			    ////
			    } else if( getValue("cansearch") != null && ((String)getValue("cansearch")).equals("yes") ) {
			        // List mode
			        Log.info("list-mode");
			        this.setValue("formmode", "list-mode");
			        
			        // FQuery for list
			        String tsoql = "select x from " + tModule + "." + tName; 
			        FQuery toql = FQuery.parseOql(tsoql);
			        toql.addOrder("{_sort}");
			        String tsql = toql.generateSql(FQuery.ON_LIST, aContext);
			        
			        String coltitles = toql.columnstitle;
			        Log.info(" generating listtable coltitles: " + coltitles, tsql);
			        //this.setValue("listsql", tsql);
			        
			        Log.info("FORM in list-mode. Generating table with SQL " + tsql);
			        /**
					FResult result = ORM.getInstance().oqltoarrayddtotal(aContext, toql);
					//Log.info("FORM result ", result);
					FResult result2 = result; //result.toArray(0);
					Log.info("FORM result2 ", result2);
					**/
			        // Build table from result
			        table listtable = (table)this.findChildOfType("table", "id", this.id + "_listtable");
			        if( listtable == null ) {
			            Log.info("Listtable not found, creating");
			            listtable = new table();
			            listtable.setValue("id", this.id + "_listtable");
			            listtable.setValue("name", this.id + "_listtable");
			            listtable.setValue("sticky", "header");
			            listtable.setValue("pagination", "50");
			            listtable.setValue("cansearch", "yes");
			            listtable.setValue("cansort", "yes");
			            listtable.setValue("multiplerowselect", this.getValue("multiplerowselect"));
			            listtable.setValue("detailwindow", "#" + aContext.get("_module") + "/" + aContext.mainComponent.getName() + "?id=");
			            listtable.setValue("sortby", "id desc");
			            listtable.setValue("renderoptions", "client");
			            this.addChild(listtable);
			        }
			        //listtable.setValue("datasource_oql", tsoql);
			        
			        listtable.setValue("columnstitle", coltitles);
			        listtable.setValue("datasource_sql", tsql);
			        
			        //listtable.setValue("datasource", tsoql);
			        listtable.event("onopen", aContext);
			        /**
			        Log.info("FORM build rows from result");
			        //listtable.buildRowsFromResult(result2);
			        listtable.clearChildren();   // @todo only update children which changes/added/removed
			        int totalrows = result2.size();
			        tr torender = null;
			        String tid = "";
			        
			        // Row with titles
			        tr trheader = new tr();
			        trheader.setValue("id", listtable.getId() + "_header");
			        trheader.setValue("name", listtable.getId() + "_header");
			        trheader.setValue("type", "header");
			        trheader.buildHeaderFromFClass(ORM.getInstance().getFClass(tModule + "." + tName));
			        listtable.addChild(trheader);
			        
			        for(int i = 0; i < totalrows; i++) {
			            FRow row = result2.get(i);
			            // Clone and add to father
			            torender = new tr();
			            tid = listtable.getId() + "[" + i + "]";
			            torender.setValue("id", tid);
			            torender.setValue("name", tid);
			            torender.setValue("type", "body");
			            torender.buildFromFRow(row);
			            torender.setValue("link", "#" + aContext.get("_module") + "/" + aContext.mainComponent.getName() + "?id=" + row.get("id"));
			            torender.setValue("additionalattributes", "data-linkargs='[view]'");
			            listtable.addChild(torender);
			            //torender.setValue("id", tid + "[" + i + "]");
			        }
			        if( totalrows == 0 ) {
			            torender = new tr();
			            tid = listtable.getId() + "_noresults";
			            torender.setValue("id", tid);
			            torender.setValue("name", tid);
			            torender.setValue("type", "body");
			            td ttd = new td();
			            ttd.setValue("id", tid + "td");
			            ttd.setValue("name", tid + "td");
			            ttd.setValue("alignment", "center");
			            ttd.setValue("content", "No hay resultados");
			            ttd.setValue("colspan", trheader.getChildren().size());
			            torender.addChild(ttd);
			            listtable.addChild(torender);            
			        }
			        **/
			        
			        
			        
			        
			    }
			}

        }
    


    
        // onedit EVENT
        if( LibText.stringToArray("" + this.id + ".onedit").contains(aAction) ) {
        			Log.info("form onedit " + this.id);
			this.setValue("formmode", "form-mode");

        }
    


    
        // delete EVENT
        if( LibText.stringToArray("" + this.name + ".delete").contains(aAction) ) {
        			// Delete object 
			String tcall;
			Log.getInstance().info("Form delete"); 
			// @todo Check related elements
			/**
			String terrors = this.validate(aContext);
			Log.info("Validate errors:", terrors);
			if( !terrors.equals("") ) {
			    aContext.call(aContext, "error", terrors);
			    return;
			}
			**/
			//  Beforedel event
			Log.info("ds " + getValue("datasource"));
			//Log.info( aContext.getContext("request_").hasMember("id") ? "hasmember id " : "has not member id");
			Log.info("Executing beforedel. Errors var:", aContext.get("errors"));
			super.event(aAction.replace("delete", "beforedel"), aContext);
			Log.info("Executed beforesave. Errors var:", aContext.get("errors"));
			if( aContext.get("errors") != null && aContext.get("errors").toString().trim().length() > 0 ) {
			    return;
			}
			//if( !this.isValid(aContext) ) return;
			// Delete
			String tsid = "";
			if( getValue("datasource") != null && !((String)getValue("datasource")).equals("") && aContext.getContext("request_").hasMember("id") ) { // this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id") != null ) { 
			    tsid = aContext.getContext("request_").get("id").toString(); //(String)this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get("id"); 
			    Log.getInstance().info("Form delete id" + tsid); 
			    //if( tsid != null && !tsid.equals("") ) { 
			        // Delete object 
			        Log.getInstance().info("Delete form object"); 
			        this.fobject.delete(); 
			 
			        /**
			        // Expose fobject & its attributes to context 
			        //this.fobject.buildScriptBindings(this.engine.getBindings(ScriptContext.ENGINE_SCOPE)); 
			        aContext.addContext("obj", this.fobject); 
			         
			        // Set variables on FFields 
			        this.updateFromObject(this.fobject, aContext); 
			        **/
			    //} 
			    
			    // Cartel guardado
			    tcall = "message('Registro eliminado')";
			    ((ArrayList)aContext.hash.get("calls")).add(tcall);
			}
			// Ondelete event
			super.event(aAction.replace("delete", "ondel"), aContext);
			// Redirect search or new
			if( getValue("cansearch") != null && ((String)getValue("cansearch")).equals("yes") ) {
			    if( !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "redirect") ) {
			        //tcall = "redirect('#' + window.actualobject._module + '/' + window.actualobject.name + '?')";   //window.actualobject._module %>/<%= window.actualobject.name %>?
			        tcall = "window.actualview.find('.form-search-btn').click()";
			        //#<%= window.actualobject._module %>/<%= window.actualobject.name %>?
			        ((ArrayList)aContext.hash.get("calls")).add(tcall);
			    }
			    
			} else {
			    if( !LibText.containsStartsWith(((ArrayList)aContext.hash.get("calls")), "redirect") ) {
			        //tcall = "redirect('#' + window.actualobject._module + '/' + window.actualobject.name + '?')";   //window.actualobject._module %>/<%= window.actualobject.name %>?
			        tcall = "window.actualview.find('.form-new-btn').click()";
			        //#<%= window.actualobject._module %>/<%= window.actualobject.name %>?
			        ((ArrayList)aContext.hash.get("calls")).add(tcall);
			    }
			    
			}

        }
    


	    super.event(aAction, aContext);
	}
	
	
}