package org.zheng.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zheng.demo.entity.Order;
import org.zheng.demo.entity.OrderItemId;
import org.zheng.demo.entity.OrderLineItem;
import org.zheng.demo.entity.Product;
import org.zheng.demo.entity.ProductProfile;
import org.zheng.demo.repository.OrderLineItemRepo;
import org.zheng.demo.repository.OrderRepo;
import org.zheng.demo.repository.ProductProfileRepo;
import org.zheng.demo.repository.ProductRepo;

@Service
@Transactional
public class DemoService {

	@Autowired
	private OrderLineItemRepo lineItemRepo;

	@Autowired
	private OrderRepo orderRep;

	@Autowired
	private ProductProfileRepo prodProfRepo;

	@Autowired
	private ProductRepo prodRepo;

	private Order buildOrder(final String orderName) {
		Order order = new Order();
		order.setName(orderName);
		return order;
	}

	private OrderLineItem buildOrderItem(final Order order, final String product, final Integer itemQuantity) {
		OrderItemId itemId1 = new OrderItemId();
		itemId1.setOrderId(order.getId());

		Product prod = findProduct(product);
		itemId1.setProductId(findProduct(product).getId());

		OrderLineItem item = new OrderLineItem();
		item.setId(itemId1);
		item.setOrder(order);
		item.setProduct(prod);
		item.setQuantity(itemQuantity);

		return item;
	}

	public List<OrderLineItem> getOrderItems() {
		List<OrderLineItem> found = lineItemRepo.findAll();
		if (found.isEmpty()) {
			dummyOrderData();
		} else {
			return found;
		}
		return lineItemRepo.findAll();
	}

	private Order saveOrder(final String orderDesc) {
		return orderRep.save(buildOrder(orderDesc));
	}

	private void saveOrderLineItem(final Order order, final String product, final Integer quantity) {
		lineItemRepo.save(buildOrderItem(order, product, quantity));
	}

	private void dummyOrderData() {
		Order order = saveOrder("first order");

		saveOrderLineItem(order, "product 1", 1);
		saveOrderLineItem(order, "product 2", 2);
	}

	private Product saveProduct(final String productName, final String prodDetail) {
		Product prod = new Product();
		prod.setName(productName);

		prod = prodRepo.save(prod);

		ProductProfile prodProfile = new ProductProfile();
		prodProfile.setProduct(prod);
		prodProfile.setProductDetail(prodDetail);

		prodProfRepo.save(prodProfile);

		return prod;
	}

	private Product findProduct(final String prodName) {
		List<Product> found = prodRepo.findByName(prodName);
		if (found.isEmpty()) {
			return saveProduct(prodName, "some Detail");
		}
		return found.get(0);

	}

	public List<ProductProfile> getProductProfiles() {
		List<ProductProfile> found = prodProfRepo.findAll();
		if (found.isEmpty()) {
			saveProduct("prod 1", "prod detail");
		} else {
			return found;
		}
		return prodProfRepo.findAll();
	}
}
