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

import org.hso.ecommerce.action.user.CreateDeliveryData;
import org.hso.ecommerce.api.RestServiceForDelivery;
import org.hso.ecommerce.entities.shop.CustomerOrder;
import org.hso.ecommerce.repos.shop.CustomerOrderRepository;
import org.hso.ecommerce.uimodel.DeliveryData;
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.RequestMapping;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Controller
@RequestMapping("intern/customerOrders")
public class CustomerOrderController {

    @Autowired
    private final CustomerOrderRepository customerOrderRepository = null;
    @Autowired
    private final RestServiceForDelivery restServiceForDelivery = null;

    @GetMapping("")
    public String internCustomerOrder(Model model) {
        List<CustomerOrder> orders =  customerOrderRepository.getAllOrders();

        Map<CustomerOrder, DeliveryData> customerOrderDeliveryDataMap = orders.stream().collect
                (Collectors.toMap
                (Function.identity(), c-> CreateDeliveryData.getDeliveryDataFromCustomerOrder(c,customerOrderRepository,restServiceForDelivery)));

        model.addAttribute("orderDeliveryDataMap", customerOrderDeliveryDataMap);
        return "intern/customerOrders/index";
    }

    @GetMapping("/{id}")
    public String internCustomerOrdersId(Model model,
                                         @PathVariable("id") String id
    ) {
        CustomerOrder order = customerOrderRepository.findById(Long.parseLong(id)).get();
        DeliveryData deliveryData = CreateDeliveryData.getDeliveryDataFromCustomerOrder(order, customerOrderRepository,restServiceForDelivery);

        model.addAttribute("order", order);
        model.addAttribute("deliveryData", deliveryData);

        return "intern/customerOrders/id";
    }
}
