package org.hso.ecommerce.action.warehouse;

import org.hso.ecommerce.entities.warehouse.WarehouseBookingPositionSlotEntry;

import java.util.HashSet;
import java.util.List;

public class CalculateWarehouseStatsAction {

    private List<WarehouseBookingPositionSlotEntry> entryList;

    public CalculateWarehouseStatsAction(List<WarehouseBookingPositionSlotEntry> everyCurrentEntry) {
        this.entryList = everyCurrentEntry;
    }

    public WarehouseStats finish() {
        int numArticles = calculateNumArticles();
        double efficiency = calculateEfficiency();
        double ratioUsedSlots = calculateRatioSlotsUsed();

        return new WarehouseStats(numArticles, efficiency, ratioUsedSlots);
    }

    private double calculateRatioSlotsUsed() {
        int used = 0;

        for (WarehouseBookingPositionSlotEntry entry : entryList) {
            if (entry.newSumSlot > 0) {
                used++;
            }
        }

        return ((double) used) / entryList.size();
    }

    private double calculateEfficiency() {
        double e = 0;

        for (WarehouseBookingPositionSlotEntry entry : entryList) {
            if (entry.newSumSlot > 0) {
                e += entry.newSumSlot / (double) entry.article.warehouseUnitsPerSlot;
            } else {
                e += 0;
            }
        }

        return e / entryList.size();
    }

    private int calculateNumArticles() {
        HashSet<Long> articleIds = new HashSet<>();

        for (WarehouseBookingPositionSlotEntry entry : entryList) {
            if (entry.newSumSlot > 0) {
                articleIds.add(entry.article.id);
            }
        }

        return articleIds.size();
    }

    private static class WarehouseStats {
        public int numArticles;
        public double efficiency;
        public double ratioUsedSlots;

        WarehouseStats(int numArticles, double efficiency, double ratioUsedSlots) {
            this.numArticles = numArticles;
            this.efficiency = efficiency;
            this.ratioUsedSlots = ratioUsedSlots;
        }
    }
}
