package com.alexanderlogistics;

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

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

import jakarta.inject.Inject;

/**
 * Das SteuerbescheidPlugin prüft ob
 * 
 * - die ATC Nummer aus dem Steuerbescheid in einer Ausgangsrechnung gefunden
 * wird ($taskID<5990)
 * - invoice.atc.number
 * - der Betrag "invoice.total.net"
 * - die Währung???
 * - die Positionsnummer ???
 * 
 * 
 * @author rsoika
 * @version 1.0
 * 
 */
public class SteuerbescheidPlugin extends AbstractPlugin {

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

	@Inject
	protected DocumentService documentService;

	@Inject
	KreditorDebitorService kreditorService;

	/**
	 * Prüft ob der Steuerbetrag abgerechnet ist.
	 * 
	 * 
	 **/
	@Override
	public ItemCollection run(ItemCollection workitem, ItemCollection event) throws PluginException {

		String atcNummer = workitem.getItemValueString("invoice.atc.number");
		logger.info("Verify ATC-Nr.: " + atcNummer);
		double amount = workitem.getItemValueDouble("invoice.total.net");
		List<ItemCollection> invoices = findInvoices(atcNummer);

		// Beträge subtrahieren....
		double saldo = amount;
		logger.info("Found " + invoices.size() + " matching invoices...");
		for (ItemCollection invoice : invoices) {
			workitem.setItemValueUnique("$workitemRef", invoice.getUniqueID());

			// suche die Zeile in der die ATC Nummer vorkommt.
			List<ItemCollection> positionen = InvoiceUtil.explodeChildList(invoice);
			for (ItemCollection pos : positionen) {
				if (atcNummer.equals(pos.getItemValueString("atc.number"))) {
					double umsatz = pos.getItemValueDouble("datev.umsatz");
					logger.info("...Umsatz=" + umsatz);
					saldo = InvoiceUtil.round(saldo - umsatz);
				}
			}
		}

		// Update Saldo
		workitem.setItemValue("invoice.saldo", InvoiceUtil.round(saldo));

		return workitem;
	}

	/*
	 * Sucht alle Ausgansrechnungen zu einer ATC Nummer
	 */
	protected List<ItemCollection> findInvoices(String atcNumber) {
		List<ItemCollection> result = new ArrayList<ItemCollection>();
		String query = "(type:workitem OR type:workitemarchive) AND ($taskid:[5000 TO 5990])"
				+ " AND invoice.atc.number:\"" + atcNumber + "\" "
				+ " AND $workflowgroup:\"Rechnungsausgang\" ";
		try {
			result = documentService.find(query, 999, 0, "$created", false);
			return result;
		} catch (QueryException e) {
			logger.severe("Failed to get invoices: " + e.getMessage());
		}

		return result;
	}

}
