/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package enterpriseserverwar;

import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import com.sun.webui.jsf.model.Option;
import inventario.entity.Category;
import inventario.entity.Facturer;
import inventario.entity.Item;
import inventario.entity.Outcome;
import inventario.entity.Person;
import inventario.entity.Supplier;
import inventario.facade.remote.CategoryFacadeRemote;
import inventario.facade.remote.FacturerFacadeRemote;
import inventario.facade.remote.ItemFacadeRemote;
import inventario.facade.remote.OutcomeFacadeRemote;
import inventario.facade.remote.PersonFacadeRemote;
import inventario.facade.remote.SupplierFacadeRemote;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.FacesException;

/**
 * <p>Session scope data bean for your application.  Create properties
 *  here to represent cached data that should be made available across
 *  multiple HTTP requests for an individual user.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 *
 * @version SessionBeanWeb.java
 * @version Created on 27-11-2008, 04:19:28 PM
 * @author Daniel
 */

public class SessionBeanWeb extends AbstractSessionBean {

    @EJB
    private ItemFacadeRemote itemFacade;
    @EJB
    private OutcomeFacadeRemote outcomeFacade;
    @EJB
    private PersonFacadeRemote personFacade;
    @EJB
    private SupplierFacadeRemote supplierFacade;
    @EJB
    private FacturerFacadeRemote facturerFacade;
    @EJB
    private CategoryFacadeRemote categoryFacade;



    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>

    /**
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionBeanWeb() {
    }

    /**
     * <p>This method is called when this bean is initially added to
     * session scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * session scope.</p>
     * 
     * <p>You may customize this method to initialize and cache data values
     * or resources that are required for the lifetime of a particular
     * user session.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>This method is called when the session containing it is about to be
     * passivated.  Typically, this occurs in a distributed servlet container
     * when the session is about to be transferred to a different
     * container instance, after which the <code>activate()</code> method
     * will be called to indicate that the transfer is complete.</p>
     * 
     * <p>You may customize this method to release references to session data
     * or resources that can not be serialized with the session itself.</p>
     */
    @Override
    public void passivate() {
    }

    /**
     * <p>This method is called when the session containing it was
     * reactivated.</p>
     * 
     * <p>You may customize this method to reacquire references to session
     * data or resources that could not be serialized with the
     * session itself.</p>
     */
    @Override
    public void activate() {
    }

    /**
     * <p>This method is called when this bean is removed from
     * session scope.  Typically, this occurs as a result of
     * the session timing out or being terminated by the application.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the application.</p>
     */
    @Override
    public void destroy() {
    }
    
    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBeanWeb getApplicationBeanWeb() {
        return (ApplicationBeanWeb) getBean("ApplicationBeanWeb");
    }




    private Item[] items;
    private Facturer[] facturers;
    private Supplier[] suppliers;
    private Person[] usuarios;
    private Facturer facturerEdit;
    private Supplier supplierEdit;
    private Person person;
    private Option[] categories;
    private Option[] itemList;
    private String categorySelected;
    private List<ListaItems> listaItems;

    public List<ListaItems> getListaItems() {
        return listaItems;
    }
    
    public ListaItems[] getListaSol() {
        if(listaItems==null)
            listaItems = new ArrayList<ListaItems>();
        return (ListaItems[])listaItems.toArray(new ListaItems[0]);
    }

    public Option[] getItemList() {
        updateItemList();
        return itemList;
    }

    
    public void updateItemList(){
        Item[] los_items = (Item[]) itemFacade.findAll().toArray(new Item[0]);
        itemList = new Option[los_items.length];
        for(int i = 0; i< los_items.length; i++){
            itemList[i] = new Option(los_items[i].getId(),los_items[i].getItem_name());
        }
    }


    public Person[] getUsuarios() {
        return usuarios;
    }

    public void setUsuarios(Person[] usuarios) {
        this.usuarios = usuarios;
    }  

    public String getCategorySelected(){
        return categorySelected;
    }

    public void setCategorySelected(String categorySelected) {
        this.categorySelected = categorySelected;
    }

    public Option[] getCategories() {
        return categories;
    }


    public Category findCategory(Long id){
        return categoryFacade.find(id);
    }

    public Item findItem(Long id){
        return itemFacade.find(id);
    }


    public void updateCategories(){
        List<Category> cats = categoryFacade.findAll();
        categories = new Option[cats.size()+1];
        categories[0] = new Option("all","Todas las Categorias");
        for(int i = 0; i<cats.size();i++){
            categories[i+1] = new Option(cats.get(i).getId(), cats.get(i).getCategory_name());
        }
    }

    public void setCategories(Option[] categories) {
        this.categories = categories;
    }


    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public boolean login(String login, String pass){
        List<Person> personas = null;
        personas = personFacade.findByLogin(login,pass);

        if(personas.size()>0){
            this.person = personas.get(0);
            return true;
        }
        else{
            return false;
        }
    }


    public Facturer getFacturerEdit() {
        return facturerEdit;
    }

    public void setFacturerEdit(Facturer facturerEdit) {
        this.facturerEdit = facturerEdit;
    }

    public Supplier getSupplierEdit() {
        return supplierEdit;
    }

    public void setSupplierEdit(Supplier supplierEdit) {
        this.supplierEdit = supplierEdit;
    }

    public void updateUsuarios() {
        usuarios = (Person[]) personFacade.findAll().toArray(new Person[0]);
    }

    public void updateSuppliers() {
        suppliers = (Supplier[]) supplierFacade.findAll().toArray(new Supplier[0]);
    }

    public void updateFacturers() {
        facturers = (Facturer[]) facturerFacade.findAll().toArray(new Facturer[0]);
    }

    public void updateItems() {
        if(categorySelected == null)
            items = (Item[]) itemFacade.findAll().toArray(new Item[0]);
        else
            items = (Item[]) itemFacade.findByCategory(Long.valueOf(categorySelected)).toArray(new Item[0]);
    }

    public void addSupplier(Supplier new_supplier) {
        supplierFacade.create(new_supplier);
         updateSuppliers();
    }


    public void addCategory(Category cat){
        categoryFacade.create(cat);
        updateCategories();
    }

    public void addOutcome(Outcome sol){
        outcomeFacade.create(sol);
        this.listaItems.clear();
    }



    public void removeSupplier(Supplier supplier) {
        supplierFacade.remove(supplier);
        updateSuppliers();
    }

    public void addFacturer(Facturer new_facturer) {
        facturerFacade.create(new_facturer);
         updateFacturers();
    }

    public void removeFacturer(Facturer facturer) {
        facturerFacade.remove(facturer);
        updateFacturers();
    }

    public void removeCategory(Category cat) {
        categoryFacade.remove(cat);
    }


    public void modCategory(Category cat){
        categoryFacade.edit(cat);
    }

    public void modSupplier(Supplier sup){
        supplierFacade.edit(sup);
    }

    public void modFacturer(Facturer fac){
        facturerFacade.edit(fac);
    }

    public void addItem(Item new_item) {
        itemFacade.create(new_item);
    }

    public void addPerson(Person new_person){
        personFacade.create(new_person);
    }


    public Supplier[] getSuppliers() {
        return suppliers;
    }

    public Facturer[] getFacturers() {
        return facturers;
    }

    public Item[] getItems() {
        return items;
    }



}
