/*******************************************************************************
 *  Imixs Workflow 
 *  Copyright (C) 2001, 2011 Imixs Software Solutions GmbH,  
 *  http://www.imixs.com
 *  
 *  This program is free software; you can redistribute it and/or 
 *  modify it under the terms of the GNU General Public License 
 *  as published by the Free Software Foundation; either version 2 
 *  of the License, or (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
 *  General Public License for more details.
 *  
 *  You can receive a copy of the GNU General Public
 *  License at http://www.gnu.org/licenses/gpl.html
 *  
 *  Project: 
 *  	http://www.imixs.org
 *  	http://java.net/projects/imixs-workflow
 *  
 *  Contributors:  
 *  	Imixs Software Solutions GmbH - initial API and implementation
 *  	Ralph Soika - Software Developer
 *******************************************************************************/

package com.alexanderlogistics;

import java.util.List;
import java.util.logging.Logger;

import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.annotation.security.RunAs;
import javax.ejb.EJB;
import javax.ejb.Singleton;

import org.imixs.workflow.ItemCollection;
import org.imixs.workflow.engine.DocumentService;
import org.imixs.workflow.exceptions.PluginException;
import org.imixs.workflow.exceptions.QueryException;

/**
 * Der KreditorService wird verwendet um einen Kreditor zu finden oder neue
 * IBAN/BIC kombinationen aufzunehmen.
 * 
 * @author rsoika
 * 
 */

@DeclareRoles({ "org.imixs.ACCESSLEVEL.NOACCESS", "org.imixs.ACCESSLEVEL.READERACCESS",
        "org.imixs.ACCESSLEVEL.AUTHORACCESS", "org.imixs.ACCESSLEVEL.EDITORACCESS",
        "org.imixs.ACCESSLEVEL.MANAGERACCESS" })
@RolesAllowed({ "org.imixs.ACCESSLEVEL.NOACCESS", "org.imixs.ACCESSLEVEL.READERACCESS",
        "org.imixs.ACCESSLEVEL.AUTHORACCESS", "org.imixs.ACCESSLEVEL.EDITORACCESS",
        "org.imixs.ACCESSLEVEL.MANAGERACCESS" })
@Singleton
@RunAs("org.imixs.ACCESSLEVEL.MANAGERACCESS")
public class KreditorDebitorService {
    public static final String TYPE_CARGOSOFTKREDITOR = "cargosoftkreditor";

    @SuppressWarnings("unused")
    private static Logger logger = Logger.getLogger(KreditorDebitorService.class.getName());

    @EJB
    DocumentService documentService;

    /**
     * Diese Method sucht einen Kreditor/Debitor. Bei Cargosoft haben kreditoren und debitoren
     * die selbe nummer und haben nur ein führendes D/K (Absolutler Irrsinn)
     * <p>
     * Diese Methode erwartet das führende K oder D
     * 
     * @throws PluginException
     */
    public ItemCollection findCreditorDebitor(String cdtrNumber) throws PluginException {

        if (cdtrNumber==null || !(cdtrNumber.startsWith("K") || cdtrNumber.startsWith("D"))) {
            throw new PluginException(PluginException.class.getName(), "QUERY ERROR", "Invalid debitor/creditor number - prafix K/D expected!");
        }
        try {
            String query = "(type:" + TYPE_CARGOSOFTKREDITOR + ") AND (name:" + cdtrNumber + ")";
            List<ItemCollection> result = documentService.find(query, 1, 0, "$modified", true);
            if (result.size() > 0) {
                return result.get(0);

            }
        } catch (QueryException e) {
            throw new PluginException(PluginException.class.getName(), "QUERY ERROR", e.getMessage(), e);
        }

        return null;
    }

    
    /**
     * Diese Method sucht einen Kreditor. 
     * <p>
     * Diese Methode erwartet das führende K 
     * 
     * @throws PluginException
     */
    public ItemCollection findCreditor(String cdtrNumber) throws PluginException {

        if ((!cdtrNumber.startsWith("K"))) {
            cdtrNumber="K"+cdtrNumber;
        }
        try {
            String query = "(type:" + TYPE_CARGOSOFTKREDITOR + ") AND (name:" + cdtrNumber + ")";
            List<ItemCollection> result = documentService.find(query, 1, 0, "$modified", true);
            if (result.size() > 0) {
                return result.get(0);

            }
        } catch (QueryException e) {
            throw new PluginException(PluginException.class.getName(), "QUERY ERROR", e.getMessage(), e);
        }

        return null;
    }
    
    /**
     * Diese Method sucht einen Debitor. 
     * <p>
     * Diese Methode erwartet das führende D 
     * 
     * @throws PluginException
     */
    public ItemCollection findDebitor(String dbtrNumber) throws PluginException {

        if ((!dbtrNumber.startsWith("D"))) {
            dbtrNumber="D"+dbtrNumber;
        }
        try {
            String query = "(type:" + TYPE_CARGOSOFTKREDITOR + ") AND (name:" + dbtrNumber + ")";
            List<ItemCollection> result = documentService.find(query, 1, 0, "$modified", true);
            if (result.size() > 0) {
                return result.get(0);

            }
        } catch (QueryException e) {
            throw new PluginException(PluginException.class.getName(), "QUERY ERROR", e.getMessage(), e);
        }

        return null;
    }

    
    
    /**
     * Diese Methode übertragt neue IBAN/BIC kombis in den kreditor
     * 
     * @param cdtrNumber
     * @param iban
     * @param bic
     * @throws PluginException
     */
    public void addNewIBANBIC(String cdtrNumber, String iban, String bic) throws PluginException {
        ItemCollection cdtr = findCreditorDebitor(cdtrNumber);

        if (cdtr != null) {

            // Wir rotieren die nummern nach unten
            cdtr.setItemValue("cdtr.iban4", cdtr.getItemValue("cdtr.iban3"));
            cdtr.setItemValue("cdtr.bic4", cdtr.getItemValue("cdtr.bic3"));
            cdtr.setItemValue("cdtr.iban3", cdtr.getItemValue("cdtr.iban2"));
            cdtr.setItemValue("cdtr.bic3", cdtr.getItemValue("cdtr.bic2"));
            cdtr.setItemValue("cdtr.iban2", cdtr.getItemValue("cdtr.iban"));
            cdtr.setItemValue("cdtr.bic2", cdtr.getItemValue("cdtr.bic"));
            // clear slot 0
            cdtr.setItemValue("cdtr.iban", "");
            cdtr.setItemValue("cdtr.bic", "");

            // nun können wir die neue IBAN/BIC in die erste frei park position legen
            if (cdtr.getItemValueString("cdtr.iban").isEmpty()) {
                cdtr.setItemValue("cdtr.iban", iban);
                cdtr.setItemValue("cdtr.bic", bic);
                documentService.save(cdtr);
                return;
            }
            if (cdtr.getItemValueString("cdtr.iban2").isEmpty()) {
                cdtr.setItemValue("cdtr.iban2", iban);
                cdtr.setItemValue("cdtr.bic2", bic);
                documentService.save(cdtr);
                return;
            }
            if (cdtr.getItemValueString("cdtr.iban3").isEmpty()) {
                cdtr.setItemValue("cdtr.iban3", iban);
                cdtr.setItemValue("cdtr.bic3", bic);
                documentService.save(cdtr);
                return;
            }
            if (cdtr.getItemValueString("cdtr.iban4").isEmpty()) {
                cdtr.setItemValue("cdtr.iban4", iban);
                cdtr.setItemValue("cdtr.bic4", bic);
                documentService.save(cdtr);
                return;
            }

        }

    }

}
