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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.hso.ecommerce.action.warehouse.StoreSupplierOrderAction;
import org.hso.ecommerce.entities.supplier.SupplierOrder;
import org.hso.ecommerce.repos.supplier.SupplierOrderRepository;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.RedirectView;

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

	@Autowired
	private final SupplierOrderRepository supplierOrderRepository = null;
	
	@GetMapping("supplierOrders")
	public String listSuppliers(Model model) {

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

		for (SupplierOrder orders : supplierOrderRepository.findAll()) {
			totals.add(new UImodelSupplierOrder(orders));
		}

		model.addAttribute("orders", totals);

		return "intern/supplierOrders/index";
	}

	@PostMapping("/supplierOrders/store/{id}")
	public RedirectView storeOrder(@PathVariable(required = true) String id) {

		long supplierOrderID = Long.parseLong(id);

		Optional<SupplierOrder> order = supplierOrderRepository.findById(supplierOrderID);

		if (order.isPresent()) {
			// TODO call action

			System.out.println("Order is present\n");
			
			
			StoreSupplierOrderAction orderAction = new StoreSupplierOrderAction(order.get());
			
			orderAction.storeOrder();
			
			supplierOrderRepository.save(order.get());
			
		}

		return new RedirectView("../../supplierOrders/");
	}

	public class UImodelSupplierOrder {
		public long id;
		public String dateOrder;
		public String supplierName;
		public String articleName;
		public long articleId;
		public String priceNet;
		public String quantity;
		public String priceTotal;
		public boolean arrived;

		public UImodelSupplierOrder(SupplierOrder order) {
			this.id = order.id;
			this.supplierName = order.supplier.name;
			this.articleName = order.ordered.title;
			this.articleId = order.ordered.id;
			this.priceNet = String.format("%.2f", ((float) order.pricePerUnitNetCent / 100));
			this.quantity = String.valueOf(order.numberOfUnits);
			this.priceTotal = String.format("%.2f", ((float) order.totalPriceNet / 100));

			Date date = new Date();
			date.setTime(order.created.getTime());
			this.dateOrder = new SimpleDateFormat("dd.MM.yyyy").format(date);

			if (order.delivered != null) {
				arrived = true;
			} else {
				arrived = false;
			}
		}
	}
}
