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.faces.context.FacesContext;
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;

/**
 * The CargosoftController CDI Bean provides Front-End methods for the cargosoft kreditore objects.
 * <p>
 * The method search provides a suggest list searching a phrase within the
 * cargosoft creditor list (type=cargosoftkreditor).
 * 
 * @author rsoika
 *
 */
@Named
@ConversationScoped
public class CargosoftController implements Serializable {

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

 
    @Inject
    protected DocumentService documentService;
  
    private List<String> searchResult = null;


    /**
     * This method searches a text phrase within the list of cargosoft kreditor objects (type=cargosoftkreditor).
     * <p>
     * JSF Integration:
     * 
     * {@code 
     * 
     * <h:commandScript name="imixsOfficeWorkflow.mlSearch" action=
     * "#{cargosoftController.search()}" rendered="#{cargosoftController!=null}" render=
     * "cargosoft-results" /> }
     * 
     * <p>
     * JavaScript Example:
     * 
     * <pre>
     * {@code
     *  imixsOfficeWorkflow.cargosoftSearch({ item: '_invoicenumber' })
     *  }
     * </pre>
     * 
     */
    public void searchCreditor() {

        searchResult = new ArrayList<String>();
        // get the param from faces context....
        FacesContext fc = FacesContext.getCurrentInstance();
        String phrase = fc.getExternalContext().getRequestParameterMap().get("phrase");
        if (phrase==null) {
            return;
        }
       
        logger.fine("search prase '" + phrase + "'");

       
        // String input =workflowController.getWorkitem().getItemValueString(itemName);
        if (phrase == null || phrase.length() < 2) {
            return;
        }

        // die cargosoft Kreditornummer beginnt seltsamerweise mit einem K 
        // und die Debitoren mit einem D.....
        String query="(type:cargosoftkreditor) AND ( (name:K" + phrase + "*) OR (name:D" + phrase + "*)  OR ("+phrase.toLowerCase() + "*) )";
       
        try {
            List<ItemCollection> result = documentService.find(query, 20, 0);
            logger.info("found " + result.size() + " creditors...");
            if (result!=null) {
                for (ItemCollection cdtr: result) {
                    
                    String cdtrNo=cdtr.getItemValueString("_VENDOR_NUM");
                    // Aenderugn 22. Jun wir geben das K/D direkt witer
                    //  if (cdtrNo.startsWith("K")) {
                           // wir entfernen das führende K
                    //     cdtrNo=cdtrNo.substring(1);
                    //   }
                    searchResult.add(cdtrNo + " - "+cdtr.getItemValueString("_VENDOR_Name"));
                    //logger.finest("...add: " + cdtr.getItemValueString("_VENDOR_NUM") + " - "+cdtr.getItemValueString("_VENDOR_Name"));
                }
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        
      

    }

  
  


    public List<String> getSearchResult() {
        return searchResult;
    }

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

}
