package com.alexanderlogistics;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
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.engine.index.Category;
import org.imixs.workflow.engine.index.SearchService;

/**
 * Der InvoiceAnalyseController dient zur Auswertung der Sachprüfungs WOrklfow
 * Schritte. Die Analyse Seite ist büer das Admin Menü erreichbar.
 * 
 * @author rsoika
 *
 */
@Named
@ConversationScoped
public class InvoiceAnalyseController implements Serializable {

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

	@Inject
	protected DocumentService documentService;

	@Inject
	SearchService searchService;

	Category sachpruefung;
	Category verteilung;
	Category buchhaltung;

	private ItemCollection filter;

	public ItemCollection getFilter() {
		if (filter == null) {
			filter = new ItemCollection();
			// compute start stop based on current month
			YearMonth startYearMonth = YearMonth.now();
			java.time.LocalDate startOfMonthDate = startYearMonth.atDay(1);
			java.time.LocalDate endOfMonthDate = startYearMonth.atEndOfMonth();
			filter.setItemValue("start",
					java.util.Date.from(startOfMonthDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
			filter.setItemValue("stop",
					java.util.Date.from(endOfMonthDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
		}
		return filter;
	}

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

	public Category getSachpruefung() {
		return sachpruefung;
	}

	public Category getVerteilung() {
		return verteilung;
	}

	public Category getBuchhaltung() {
        return buchhaltung;
    }

    public int totalCountByCategory(Category cat) {
		int result = 0;

		Collection<Integer> allCounts = cat.getLabels().values();
		result = allCounts.stream().reduce(0, Integer::sum);

		return result;
	}

	/**
	 * Fuert verschiedene Queries aus um eine Analyse der Sachprufung durchzuführen.
	 */
	public void analyse() {

		logger.info("start analyse....");
		verteilung = null;
		sachpruefung = null;
		Date start = filter.getItemValueDate("start");
		Date stop = filter.getItemValueDate("stop");

		logger.info("...daterange=" + start + " - " + stop);

		// serach date range?
		String sDateFrom = "191401070000"; // because * did not work here
		String sDateTo = "211401070000";
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmm");

		if (start != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(start);
			sDateFrom = dateformat.format(cal.getTime());
		}
		if (stop != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(stop);
			cal.add(Calendar.DATE, 1);
			sDateTo = dateformat.format(cal.getTime());
		}

		// query Verteilung
		String query = "(type:workitem OR type:workitemarchive) ";
		if (start != null || stop != null) {
			query += "AND (taxonomy.verteilung.stop:[" + sDateFrom + " TO " + sDateTo + "]) ";
		}
		logger.info(query);
		List<Category> taxResult = searchService.getTaxonomyByQuery(query, "taxonomy.verteilung.stop.by");
		if (taxResult.size() > 0) {
			verteilung = taxResult.get(0);

		}

		// query Sachprüfung
		query = "(type:workitem OR type:workitemarchive) ";
		if (start != null || stop != null) {
			query += "AND (taxonomy.sachpruefung.stop:[" + sDateFrom + " TO " + sDateTo + "]) ";
		}
		logger.info(query);
		taxResult = searchService.getTaxonomyByQuery(query, "taxonomy.sachpruefung.stop.by");
		if (taxResult.size() > 0) {
			sachpruefung = taxResult.get(0);

		}
		
		// query Buchhaltung
        query = "(type:workitem OR type:workitemarchive) ";
        if (start != null || stop != null) {
            query += "AND (taxonomy.buchhaltung.stop:[" + sDateFrom + " TO " + sDateTo + "]) ";
        }
        logger.info(query);
        taxResult = searchService.getTaxonomyByQuery(query, "taxonomy.buchhaltung.stop.by");
        if (taxResult.size() > 0) {
            buchhaltung = taxResult.get(0);

        }

	}

	/**
	 * This method reset the search and input state.
	 */
	public void reset() {
		filter = new ItemCollection();
		sachpruefung = null;
		verteilung = null;
		buchhaltung = null;
		logger.fine("reset");
	}

}
