package org.hso.ecommerce.controller.intern.suppliers;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.hso.ecommerce.entities.supplier.ArticleOffer;
import org.hso.ecommerce.repos.shop.ArticleRepository;
import org.hso.ecommerce.repos.shop.OffersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/intern/")
public class SupplierOfferController {

	@Autowired
	private final OffersRepository offersRepository = null;

	@Autowired
	private final ArticleRepository articleRepository = null;

	@GetMapping("supplierOffers")
	public String internListedArticles(Model model) {

		List<UImodelOfferedArticle> totals = new ArrayList<>();

		for (ArticleOffer article : offersRepository.findAll()) {
			UImodelOfferedArticle tmp = new UImodelOfferedArticle();
			tmp.addData(article, articleRepository.findArticleIDByRelatedID(article.id));
			totals.add(tmp);
		}

		model.addAttribute("OfferedArticles", totals);
		return "intern/offeredArticles/index";
	}

	public class UImodelOfferedArticle {

		public long offerId;
		public String title;
		public String manufacturer;
		public String articleNumber;
		public String supplierName;
		public String price;
		public String ads;
		public int listedArticleId;
		public boolean offerIsListed; // true --> offered article is listed

		public void addData(ArticleOffer article, Optional<Integer> listedArticleId) {

			this.offerId = article.id;
			this.title = article.title;
			this.manufacturer = article.manufacturer;
			this.articleNumber = article.articleNumber;
			this.supplierName = article.cheapestSupplier.name;
			this.price = String.format("%.2f", ((float) article.pricePerUnitNet / 100));
			this.ads = (article.shouldBeAdvertised) ? "Ja" : "Nein";

			if (listedArticleId.isPresent()) {
				// this offer is listed --> show link
				this.listedArticleId = listedArticleId.get();
				offerIsListed = true;
			} else {
				// this offer is not listed
				offerIsListed = false;
			}
		}
	}
}
