package com.alexanderlogistics.mahnlauf;

import java.io.Serializable;
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.faces.data.WorkflowController;

import com.alexanderlogistics.InvoiceUtil;

/**
 * Der InkassoController dient dazu eine bereits zugewiesene Rechnung
 * wieder aus dem Inkasso zu entfernen.
 * <p>
 * Zusätzlich bietet er die Summenberechnung an, bei der die Gutschriften
 * abgezogen werden.
 * 
 * @author rsoika
 *
 */
@Named
@ConversationScoped
public class InkassoController implements Serializable {

    private static final long serialVersionUID = 1L;

    private static Logger logger = Logger.getLogger(InkassoController.class.getName());

    @Inject
    protected WorkflowController workflowController;

    @Inject
    protected DocumentService documentService;

    /**
     * This method computes the sum for a given item in a list of workitems. The
     * result is rounded to 2 digits.
     * <p>
     * Gutschriften werden abgezogen
     * 
     * @param refids - list of workitem uniqueIds
     * @param item   - name of the item to summarize
     * @return sum rounded to 2 digits
     */
    public double calculateSum(List<String> refids, String item) {
        double result = 0;
        for (String id : refids) {
            ItemCollection doc = documentService.load(id);
            if (doc != null) {
                result = result + doc.getItemValueDouble(item);
              
            } else {
                logger.warning("invalid read access to calculate sum");
            }
        }
        // rond with 2 digits
        return InvoiceUtil.round(result);

    }

    /**
     * This method removes an uniqueid form the item $workitemref
     */
    @SuppressWarnings("unchecked")
    public void removeInvoice(String id) {

        List<String> refList = workflowController.getWorkitem().getItemValue("$workitemref");

        refList.remove(id);
        workflowController.getWorkitem().setItemValue("$workitemref", refList);
    }

}
