package com.alexanderlogistics;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.poi.ss.usermodel.CellCopyPolicy;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.imixs.marty.team.TeamService;
import org.imixs.workflow.FileData;
import org.imixs.workflow.ItemCollection;
import org.imixs.workflow.ItemCollectionComparator;
import org.imixs.workflow.engine.DocumentService;
import org.imixs.workflow.engine.WorkflowService;
import org.imixs.workflow.exceptions.AdapterException;
import org.imixs.workflow.exceptions.PluginException;
import org.imixs.workflow.exceptions.QueryException;
import org.imixs.workflow.office.config.ConfigService;
import org.imixs.workflow.poi.POIFindReplaceAdapter;

import jakarta.inject.Inject;

/**
 * Der OPListExportAdapterByWeek ist ählnlich dem Der OPListExportAdapter. Er
 * erzeugt eine Excel tabelle mit allen offenen Rechnungen und gruppiert diese
 * nach Abteilungen und KW
 * 
 * Der OPListExportAdapterByWeek importiert eine Excel Datei aus einem Textblock
 * 
 * <pre>
 * {@code
        <opliste name="textblock">textblock-ref</opliste>
        <opliste name="template">filename</opliste>
        <opliste name="targetname">filename</opliste>
   }
 * </pre>
 * <p>
 * Der Adapter erweitert den POIAdapter somit können felder aktualisiert werden
 * (siehe POIFineReplaceAdapter).
 * 
 * <p>
 * Der Adapter kopiert die Rechnungsdaten in neue Zeilen, welche ab Zeilnenummer
 * 16 eingefügt werden.
 * <p>
 * 
 * Abschliessend wird die Zelle 'TOTAL' noch aktualisiert.
 * 
 * @version 1.0
 * @author rsoika
 */
public class OPListExportAdapterByWeek extends POIFindReplaceAdapter {

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

    final String TYPE_TEXTBLOCK = "textblock";

    @Inject
    WorkflowService workflowService;

    @Inject
    DocumentService documentService;

    @Inject
    TeamService teamService;

    @Inject
    ConfigService configService;

    @Inject
    OPListExportService opListExportService;

    // cache for all invoices grouped by week
    Map<String, List<ItemCollection>> invoiceMap = null;

    /**
     * This method finds or create the Zahlungsavis and adds a reference
     * ($workitemref) to the current invoice.
     * 
     * @throws PluginException
     */
    @SuppressWarnings("unchecked")
    @Override
    public ItemCollection execute(ItemCollection document, ItemCollection event)
            throws AdapterException, PluginException {

        // read the opliste options
        ItemCollection evalItemCollection = workflowService.evalWorkflowResult(event, "opliste", document, false);
        if (evalItemCollection == null) {
            throw new PluginException(OPListExportAdapterByWeek.class.getSimpleName(), OPListExportService.ERROR_CONFIG,
                    "missing op-list configuration in model event - please check model configuration");
        }

        // ermittle die Hauptwährungen
        ItemCollection configItemCollection = configService.loadConfiguration("AGL_CONFIGURATION");
        List<String> currencyList = configItemCollection.getItemValue("currency.out");
        if (currencyList == null || currencyList.size() < 2) {
            throw new PluginException(OPListExportAdapter.class.getSimpleName(), OPListExportService.ERROR_CONFIG,
                    "missing Currency configuration - please check parameters");
        }
        String currency1 = currencyList.get(0);
        String currency2 = currencyList.get(1);

        String textblock = evalItemCollection.getItemValueString("textblock");
        String template = evalItemCollection.getItemValueString("template");
        String targetName = evalItemCollection.getItemValueString("target-name");
        // adapt text....
        targetName = workflowService.adaptText(targetName, document);
        appendExcelTemplate(document, textblock, template, targetName);

        logger.info("... loading poi configuration..");
        // Process POI instructions
        // read the config
        ItemCollection poiConfig = workflowService.evalWorkflowResult(event, "poi-update", document, false);
        if (poiConfig == null || !poiConfig.hasItem("findreplace")) {
            throw new PluginException(POIFindReplaceAdapter.class.getSimpleName(), CONFIG_ERROR,
                    "missing poi configuration");
        }
        List<String> replaceDevList = poiConfig.getItemValue("findreplace");
        String eval = poiConfig.getItemValueString("eval");
        try {
            logger.info("... update template with normal poi information..");
            this.updateFileData(document.getFileData(targetName), document, replaceDevList, eval);

            insertInvoiceRows(document, targetName, currency1, currency2);
        } catch (PluginException | IOException | QueryException e) {
            throw new PluginException(OPListExportAdapterByWeek.class.getSimpleName(), OPListExportService.ERROR_CONFIG,
                    "failed to update op-liste: " + e.getMessage());
        }
        logger.info("... completed!");
        return document;
    }

    /**
     * This helper method inserts a row for each invoice of the OPListe at row 16
     * into the excel template file
     * <p>
     * First the method computes all Departments and insert them at C10
     * <p>
     * The method copies the Row A16 as a reference row
     * <p>
     * The named cell 'TOTAL' should contain the summary formula. It will be
     * evaluated at the end.
     * 
     * @throws PluginException
     * @throws QueryException
     */
    private void insertInvoiceRows(ItemCollection document, String fileName, String currency1,
            String currency2)
            throws PluginException, QueryException {

        Map<String, Double> totalsUeberfaelligCurrency1 = new HashMap<String, Double>();
        Map<String, Double> totalsFaelligCurrency1 = new HashMap<String, Double>();
        Map<String, Double> totalsUeberfaelligCurrency2 = new HashMap<String, Double>();
        Map<String, Double> totalsFaelligCurrency2 = new HashMap<String, Double>();
        List<String> spaceNames = new ArrayList<String>();

        // compute all departments
        List<ItemCollection> spaces = teamService.getSpaces();
        // sort by space.name
        Collections.sort(spaces, new ItemCollectionComparator("space.name", true));

        Map<String, WeekInvoiceData> weekDataMap = new HashMap<String, WeekInvoiceData>();
        FileData fileData = document.getFileData(fileName);

        // load XSSFWorkbook
        XSSFWorkbook doc = null;
        try (InputStream imputStream = new ByteArrayInputStream(fileData.getContent())) {
            doc = new XSSFWorkbook(imputStream);

            // compute current week
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());
            int weekNumber = calendar.get(Calendar.WEEK_OF_YEAR);
            int year = calendar.get(Calendar.YEAR);
            String currentWeek = year + "/";
            if (weekNumber < 10) {
                currentWeek = currentWeek + "0" + weekNumber;
            } else {
                currentWeek = currentWeek + weekNumber;
            }

            CellStyle headerCellStyle = doc.createCellStyle();
            // fill foreground color ...
            headerCellStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.index);
            // and solid fill pattern produces solid grey cell fill
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            // NOTE: we only take the first sheet !
            XSSFSheet sheet = doc.getSheetAt(0);

            // First we create a column for each Space.....
            XSSFRow rowSpacesLabels = sheet.getRow(9);
            XSSFRow referenceRowSpacesCurrencies = sheet.getRow(10);
            XSSFRow referenceRowValues = sheet.getRow(11);
            XSSFRow referenceRowCurrentWeek = sheet.getRow(12);

            XSSFRow referenceRowTotal = sheet.getRow(15);

            // Aktuelle KW berechnen
            calendar.setTime(new Date());
            int currentWeekNumber = calendar.get(Calendar.WEEK_OF_YEAR);
            int currentYear = calendar.get(Calendar.YEAR);
            String currentWeekCategory = currentYear + "/";
            if (currentWeekNumber < 10) {
                currentWeekCategory = currentWeekCategory + "0" + currentWeekNumber;
            } else {
                currentWeekCategory = currentWeekCategory + currentWeekNumber;
            }

            /*
             * --- Phase 1 -------------------------------------------------------
             * Im folgenden fügen wir erst einmal in der Kopfzeile zusätzlich
             * Spaltenüberschriften für jede Abteilung ein
             */
            XSSFCell cellSpaceLabelReference = rowSpacesLabels.getCell(2);
            XSSFCell cellSpaceCurrencyReference = referenceRowSpacesCurrencies.getCell(1);
            // XSSFCell cellKWTotalReference = referenceRowCurrentWeek.getCell(1);
            XSSFCell cellKWTotalReference = referenceRowTotal.getCell(14);
            int column = 1; // beginn in der 2. Spalte!
            for (ItemCollection space : spaces) {
                XSSFCell cell = null;
                String spaceName = space.getItemValueString("space.name");
                String spaceID = space.getUniqueID();
                spaceNames.add(spaceName);

                // Space currency EUR
                cell = referenceRowSpacesCurrencies.getCell(column);
                cell.copyCellFrom(cellSpaceCurrencyReference, new CellCopyPolicy());
                cell.setCellValue(currency1);

                // Space currency USD
                column++;
                cell = referenceRowSpacesCurrencies.getCell(column);
                cell.copyCellFrom(cellSpaceCurrencyReference, new CellCopyPolicy());
                cell.setCellValue(currency2);

                // Space Label
                cell = rowSpacesLabels.getCell(column);
                cell.setCellValue(spaceName);

                // create two new cells...
                column++;
                cell = rowSpacesLabels.createCell(column);
                cell.copyCellFrom(cellSpaceLabelReference, new CellCopyPolicy());
                cell.setCellValue("");

                cell = rowSpacesLabels.createCell(column);
                cell.copyCellFrom(cellSpaceLabelReference, new CellCopyPolicy());
                cell.setCellValue("");

                logger.info("...grouping invoices by week...");
                // collect all invoices for this space grouped by week....
                groupInvoicesByWeek(spaceID, spaceName, weekDataMap, currency1);

                // init totals
                for (String name : spaceNames) {
                    totalsUeberfaelligCurrency1.put(name, 0.0);
                    totalsFaelligCurrency1.put(name, 0.0);
                    totalsUeberfaelligCurrency2.put(name, 0.0);
                    totalsFaelligCurrency2.put(name, 0.0);
                }
            }
            totalsUeberfaelligCurrency1.put("TOTAL", 0.0);
            totalsFaelligCurrency1.put("TOTAL", 0.0);
            totalsUeberfaelligCurrency2.put("TOTAL", 0.0);
            totalsFaelligCurrency2.put("TOTAL", 0.0);
            /*
             * --- Phase 2 -------------------------------------------------------
             * Nun bilden wir nochmal 2 weitere Spalten am Ende um eine Summenbildung in
             * EUR/USD pro KW zu ermöglichen
             */
            XSSFCell cell = null;
            // column++;
            // Space currency EUR
            cell = referenceRowSpacesCurrencies.getCell(column);
            cell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
            cell.setCellValue(currency1);
            cell = rowSpacesLabels.getCell(column);
            cell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
            cell.setCellValue("");

            // Space currency USD
            column++;
            cell = referenceRowSpacesCurrencies.getCell(column);
            cell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
            cell.setCellValue(currency2);

            // Space Label
            cell = rowSpacesLabels.getCell(column);
            cell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
            cell.setCellValue("Total");

            /*
             * --- Phase 3 -------------------------------------------------------
             * now build a new row for each week and print out the collected invoice data
             * first iterate over all objects and collect all known weeks and sort them into
             * a ordered list....
             */
            List<String> sortedWeekList = new ArrayList<String>();
            Iterator<Map.Entry<String, WeekInvoiceData>> iterator = weekDataMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, WeekInvoiceData> entry = iterator.next();
                WeekInvoiceData weekInvoiceData = entry.getValue();
                if (!sortedWeekList.contains(weekInvoiceData.week)) {
                    sortedWeekList.add(weekInvoiceData.week);
                }
            }
            Collections.sort(sortedWeekList);

            /*
             * --- Phase 4 -------------------------------------------------------
             * Nun müssen wir so viele Zeilen nach unten schieben wie wir gleich einfügen.
             * Dazu müssen wir kurz einen Probelauf machen um die geplante Anzahl zu
             * errechnen....
             */
            int rowPos = 11;
            int insertCount = sortedWeekList.size();
            sheet.shiftRows(rowPos + 1, 2999, insertCount, true, true);

            /*
             * --- Phase 5 -------------------------------------------------------
             * Jetzt Zahlen Zeile für Zeile einfügen....
             */
            boolean ueberFaellig = true;
            for (String week : sortedWeekList) {
                // now create a new line..
                rowPos++;
                logger.fine("--> Zeile " + rowPos + " Week=" + week);
                XSSFRow row = sheet.createRow(rowPos);

                if (week.equals(currentWeekCategory)) {
                    row.copyRowFrom(referenceRowCurrentWeek, new CellCopyPolicy());
                    ueberFaellig = false;
                } else {
                    row.copyRowFrom(referenceRowValues, new CellCopyPolicy());
                }

                // insert values
                row.getCell(0).setCellValue(week);

                // iterate over all spaceNames and test if we have any data to put it into the
                // row cells....
                column = 1;
                double kwTotalEUR = 0;
                double kwTotalUSD = 0;

                for (String name : spaceNames) {
                    String key = name + "/" + week;
                    logger.fine("search WeekInvoiceData for " + key);
                    // list of invoices
                    WeekInvoiceData weekData = weekDataMap.get(key);
                    if (weekData != null) {
                        logger.fine("  " + currency1 + "=" + weekData.totalCurrency1 + "  " + currency2 + "="
                                + weekData.totalCurrency2);
                        row.getCell(column).setCellValue(weekData.totalCurrency1);
                        column++;
                        row.getCell(column).setCellValue(weekData.totalCurrency2);
                        if (ueberFaellig) {
                            double eur = totalsUeberfaelligCurrency1.get(name);
                            eur = InvoiceUtil.round(eur + weekData.totalCurrency1);
                            totalsUeberfaelligCurrency1.put(name, eur);
                            double usd = totalsUeberfaelligCurrency2.get(name);
                            usd = InvoiceUtil.round(usd + weekData.totalCurrency2);
                            totalsUeberfaelligCurrency2.put(name, usd);
                            // saldoEUR1 = InvoiceUtil.round(saldoEUR1 + weekData.totalEUR);
                            // saldoUSD1 = InvoiceUtil.round(saldoUSD1 + weekData.totalUSD);
                        } else {
                            double eur = totalsFaelligCurrency1.get(name);
                            eur = InvoiceUtil.round(eur + weekData.totalCurrency1);
                            totalsFaelligCurrency1.put(name, eur);
                            double usd = totalsFaelligCurrency2.get(name);
                            usd = InvoiceUtil.round(usd + weekData.totalCurrency2);
                            totalsFaelligCurrency2.put(name, usd);
                            // saldoEUR2 = InvoiceUtil.round(saldoEUR2 + weekData.totalEUR);
                            // saldoUSD2 = InvoiceUtil.round(saldoUSD2 + weekData.totalUSD);
                        }
                        kwTotalEUR = kwTotalEUR + weekData.totalCurrency1;
                        kwTotalUSD = kwTotalUSD + weekData.totalCurrency2;
                        column++;
                    } else {
                        logger.fine("...... NOT FOUND");
                        // skip columns
                        column = column + 2;
                    }
                }
                // KW Summe anzeigen
                if (week.equals(currentWeekCategory)) {
                    XSSFCell kwTotalCell = row.getCell(column);
                    // kwTotalCell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
                    kwTotalCell.setCellValue(kwTotalEUR);

                    column++;
                    // row.getCell(column).setCellValue(kwTotalUSD);
                    kwTotalCell = row.getCell(column);
                    // kwTotalCell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
                    kwTotalCell.setCellValue(kwTotalUSD);

                } else {
                    XSSFCell kwTotalCell = row.getCell(column);
                    kwTotalCell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
                    kwTotalCell.setCellValue(kwTotalEUR);

                    column++;
                    // row.getCell(column).setCellValue(kwTotalUSD);
                    kwTotalCell = row.getCell(column);
                    kwTotalCell.copyCellFrom(cellKWTotalReference, new CellCopyPolicy());
                    kwTotalCell.setCellValue(kwTotalUSD);

                }

                // store totals
                if (ueberFaellig) {
                    double eur = totalsUeberfaelligCurrency1.get("TOTAL");
                    eur = InvoiceUtil.round(eur + kwTotalEUR);
                    totalsUeberfaelligCurrency1.put("TOTAL", eur);
                    double usd = totalsUeberfaelligCurrency2.get("TOTAL");
                    usd = InvoiceUtil.round(usd + kwTotalUSD);
                    totalsUeberfaelligCurrency2.put("TOTAL", usd);
                } else {
                    double eur = totalsFaelligCurrency1.get("TOTAL");
                    eur = InvoiceUtil.round(eur + kwTotalEUR);
                    totalsFaelligCurrency1.put("TOTAL", eur);
                    double usd = totalsFaelligCurrency2.get("TOTAL");
                    usd = InvoiceUtil.round(usd + kwTotalUSD);
                    totalsFaelligCurrency2.put("TOTAL", usd);
                }

            }
            // delete reference rows
            logger.finest("..shift 12 to " + rowPos);
            sheet.shiftRows(12, rowPos, -1, true, true);
            sheet.shiftRows(rowPos + 2, rowPos + 6, -3, true, true);

            /*
             * --- Phase 6 -------------------------------------------------------
             * now lets update the totals...
             * Überfällig
             */
            int _rowNo = sortedWeekList.size() + 11;
            XSSFRow rowUeberFaellig = sheet.getRow(_rowNo);
            XSSFRow rowFaellig = sheet.getRow(_rowNo + 1);
            XSSFRow rowTotal = sheet.getRow(_rowNo + 2);
            column = 1;
            XSSFCell totalCell = null;
            for (String name : spaceNames) {
                totalCell = rowUeberFaellig.getCell(column);
                totalCell.setCellValue(totalsUeberfaelligCurrency1.get(name));
                totalCell = rowFaellig.getCell(column);
                totalCell.setCellValue(totalsFaelligCurrency1.get(name));
                totalCell = rowTotal.getCell(column);
                totalCell.setCellValue(totalsUeberfaelligCurrency1.get(name) + totalsFaelligCurrency1.get(name));
                column++;
                totalCell = rowUeberFaellig.getCell(column);
                totalCell.setCellValue(totalsUeberfaelligCurrency2.get(name));
                totalCell = rowFaellig.getCell(column);
                totalCell.setCellValue(totalsFaelligCurrency2.get(name));
                totalCell = rowTotal.getCell(column);
                totalCell.setCellValue(totalsUeberfaelligCurrency2.get(name) + totalsFaelligCurrency2.get(name));
                column++;
            }
            // totals
            totalCell = rowUeberFaellig.getCell(column);
            totalCell.setCellValue(totalsUeberfaelligCurrency1.get("TOTAL"));
            totalCell = rowFaellig.getCell(column);
            totalCell.setCellValue(totalsFaelligCurrency1.get("TOTAL"));
            totalCell = rowTotal.getCell(column);
            totalCell.setCellValue(totalsUeberfaelligCurrency1.get("TOTAL") + totalsFaelligCurrency1.get("TOTAL"));
            column++;
            totalCell = rowUeberFaellig.getCell(column);
            totalCell.setCellValue(totalsUeberfaelligCurrency2.get("TOTAL"));
            totalCell = rowFaellig.getCell(column);
            totalCell.setCellValue(totalsFaelligCurrency2.get("TOTAL"));
            totalCell = rowTotal.getCell(column);
            totalCell.setCellValue(totalsUeberfaelligCurrency2.get("TOTAL") + totalsFaelligCurrency2.get("TOTAL"));

            // delete placeholder row
            sheet.shiftRows(_rowNo, _rowNo + 3, -1);

            // write back the file
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            doc.write(byteArrayOutputStream);

            byte[] newContent = byteArrayOutputStream.toByteArray();
            FileData fileDataNew = new FileData(fileData.getName(), newContent, fileData.getContentType(), null);
            // update the fileData
            document.addFileData(fileDataNew);
            logger.finest("......new document added");

        } catch (IOException e) {
            throw new PluginException(OPListExportAdapterByWeek.class.getSimpleName(), OPListExportService.ERROR_CONFIG,
                    "failed to update opliste: " + e.getMessage());
        } finally {
            if (doc != null) {
                try {
                    doc.close();
                } catch (IOException e) {
                    logger.severe("Failed to close workbook: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * This method loads a text-block for a specified ref and appends the named
     * fileData object of this document.
     * 
     * @param document
     * @throws PluginException
     */
    private void appendExcelTemplate(ItemCollection document, String textblockRef, String template, String targetName)
            throws PluginException {

        if ((template == null || template.isEmpty()) || (textblockRef == null || textblockRef.isEmpty())) {
            throw new PluginException(OPListExportAdapterByWeek.class.getSimpleName(), OPListExportService.ERROR_CONFIG,
                    "invalid op-list configuration in model event - textblock/template reference not defined!");
        }

        // load the text block
        FileData fileData = opListExportService.loadTextBlockFileData(textblockRef, template);

        // do we found the document?
        if (fileData == null) {
            throw new PluginException(OPListExportAdapterByWeek.class.getSimpleName(), OPListExportService.ERROR_CONFIG,
                    "invalid op-list configuration in model event - template=" + template + " not found!");
        }
        fileData.setName(targetName);
        // append document
        logger.info("...append new op-list Template: " + targetName);

        document.addFileData(fileData);

    }

    /**
     * Diese Methode gruppiert eine Rechnungsliste nach Kalenderwoche
     * 
     * @param spaceID - Space Ref to select a list of invoices assoicated with a
     *                space
     * @param cache   - a local cache storing all invoices by week
     * 
     * 
     */
    private void groupInvoicesByWeek(String spaceID, String spaceName,
            Map<String, WeekInvoiceData> cache, String currency1) {

        logger.info("...group invoices for " + spaceName + "/" + spaceID);
        try {
            List<ItemCollection> invoices = documentService.find(
                    "$modelversion:rechnungsausgang-* AND type:workitem AND $uniqueidref:" + spaceID, 9999, 0,
                    "invoice.number", false);

            logger.fine("   found " + invoices.size() + " for space " + spaceName);
            for (ItemCollection invoice : invoices) {
                // compute Week
                Date dueDate = invoice.getItemValueDate("invoice.duedate");
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(dueDate);
                int weekNumber = calendar.get(Calendar.WEEK_OF_YEAR);
                int year = calendar.get(Calendar.YEAR);
                String weekCategory = year + "/";
                if (weekNumber < 10) {
                    weekCategory = weekCategory + "0" + weekNumber;
                } else {
                    weekCategory = weekCategory + weekNumber;
                }
                // haben wir shon ein listchen?

                String key = spaceName + "/" + weekCategory;
                logger.fine("   ....building weekInvoiceData object for " + key);

                WeekInvoiceData weekData = cache.get(key);
                if (weekData == null) {
                    weekData = new WeekInvoiceData(spaceName, weekCategory);
                }
                // Jetzt Rechnung addieren
                weekData.add(invoice, currency1);
                cache.put(key, weekData);
            }

        } catch (

        QueryException e) {
            e.printStackTrace();
        }

    }
}

/**
 * Data Element for invoice totals per week and space
 */
class WeekInvoiceData {

    String week;
    String spaceName;
    double totalCurrency1;
    double totalCurrency2;

    public WeekInvoiceData(String spaceName, String week) {
        this.spaceName = spaceName;
        this.week = week;
    }

    public void add(ItemCollection invoice, String currency1) {
        String spaceName = invoice.getItemValueString("space.name");
        String currency = invoice.getItemValueString("invoice.currency");
        // Double total = invoice.getItemValueDouble("invoice.total");
        Double total = invoice.getItemValueDouble("invoice.saldo");
        if (currency1.equals(currency)) {
            totalCurrency1 = totalCurrency1 + total;
        } else {
            totalCurrency2 = totalCurrency2 + total;

        }

    }

}