package org.hso.ecommerce.action.cronjob;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.hso.ecommerce.action.cronjob.ReadSupplierDataAction.ArticleIdentifier;
import org.hso.ecommerce.action.cronjob.ReadSupplierDataAction.Offer;
import org.hso.ecommerce.api.data.Article;
import org.hso.ecommerce.entities.supplier.ArticleOffer;

public class UpdateOffersAction {
    private List<ArticleOffer> offers;
    private HashMap<ArticleIdentifier, Offer> cheapestOffer;

    public UpdateOffersAction(List<ArticleOffer> offers, HashMap<ArticleIdentifier, Offer> cheapestOffer) {
        this.offers = offers;
        this.cheapestOffer = cheapestOffer;
    }

    private HashMap<ArticleIdentifier, ArticleOffer> mapOffers() {
        HashMap<ArticleIdentifier, ArticleOffer> map = new HashMap<>();
        for (ArticleOffer offer : offers) {
            ArticleIdentifier identifier = new ArticleIdentifier(offer.manufacturer, offer.articleNumber);
            map.put(identifier, offer);
        }
        return map;
    }

    public List<ArticleOffer> finish() {
        HashMap<ArticleIdentifier, ArticleOffer> availableOffers = mapOffers();

        // Reset all advertise-flags and supplier relations first. They are set again below.
        for (ArticleOffer offer : availableOffers.values()) {
            offer.shouldBeAdvertised = false;
            offer.cheapestSupplier = null;
        }

        for (Entry<ArticleIdentifier, Offer> cheapestOffer : cheapestOffer.entrySet()) {
            String manufacturer = cheapestOffer.getKey().manufacturer;
            String articleNumber = cheapestOffer.getKey().articleNumber;
            ArticleOffer currentOffer = availableOffers.get(cheapestOffer.getKey());
            if (currentOffer == null) {
                currentOffer = new ArticleOffer();
                currentOffer.manufacturer = manufacturer;
                currentOffer.articleNumber = articleNumber;
                offers.add(currentOffer);
            }
            Article currentOfferedArticle = cheapestOffer.getValue().apiSupplier.findArticle(manufacturer,
                    articleNumber);
            currentOffer.title = currentOfferedArticle.title;
            currentOffer.vatPercent = currentOfferedArticle.vatPercent;
            currentOffer.cheapestSupplier = cheapestOffer.getValue().dbSupplier;
            currentOffer.pricePerUnitNet = currentOfferedArticle.pricePerUnitNet;

            // Set advertise-flag if any supplier wants it to be set
            if (currentOfferedArticle.shouldBeAdvertised) {
                currentOffer.shouldBeAdvertised = true;
            }
        }
        return offers;
    }
}
