package com.alexanderlogistics;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.imixs.workflow.ItemCollection;
import org.imixs.workflow.engine.DocumentService;
import org.imixs.workflow.exceptions.QueryException;
import org.imixs.workflow.faces.util.LoginController;

/**
 * The InvoiceDispatchController loads open workitems for the current user
 * 
 * @author rsoika
 *
 */
@Named
@ConversationScoped
public class InvoiceDispatchController implements Serializable {

    private static final long serialVersionUID = 1L;
    private static Logger logger = Logger.getLogger(InvoiceDispatchController.class.getName());

    @Inject
    protected DocumentService documentService;

    @Inject
    protected LoginController loginController;

    private List<ItemCollection> invoices = null;
    private String filter =null;

    
    public String getFilter() {
        return filter;
    }

    public void setFilter(String filter) {
        this.filter = filter;
    }

    /**
     * This method searches the invoices.
     * <ui:param name="query" value="(type:workitem) AND
     * ($modelversion:rechnungseingang-de*) AND ($taskid:5100) AND
     * ($owner:#{user})"></ui:param> <ui:param name="invoiceList" value=
     * "#{workflowController.documentService.find(query,30,0)}"></ui:param>
     * 
     */
    public void searchInvoices() {
        long l=System.currentTimeMillis();
        String owner = loginController.getUserPrincipal();
        String query = "(type:workitem) AND ($modelversion:rechnungseingang-de*) AND ($taskid:5100) AND ($owner:"
                + owner + ")";

        if (filter!=null && !filter.isEmpty()) {
            query=query + " AND "+filter.toLowerCase() +"*";
        }

        logger.info("search:  " + query);
        try {
            invoices = documentService.findStubs(query, 2000, 0, "$created", false);
            logger.info("found " + invoices.size() + " invoices for StapelVerarbeitung in " + (System.currentTimeMillis()-l) + "ms");
        } catch (QueryException e) {
            e.printStackTrace();
            reset();
        }

    }

    public List<ItemCollection> getInvoices() {
        if (invoices == null) {
            searchInvoices();
        }
        return invoices;
    }

    /**
     * This method reset the search and input state.
     */
    public void reset() {
        invoices = new ArrayList<ItemCollection>();
        logger.fine("reset");
    }

}
