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

import org.hso.ecommerce.action.warehouse.CalculateWarehouseStatsAction;
import org.hso.ecommerce.entities.warehouse.WarehouseBookingPositionSlotEntry;
import org.hso.ecommerce.repos.warehouse.SlotRepository;
import org.hso.ecommerce.repos.warehouse.WarehouseBookingPositionSlotEntryRepository;
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;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/intern/warehouse/")
public class SlotsController {

    @Autowired
    private final WarehouseBookingPositionSlotEntryRepository warehouseBookingPositionSlotEntryRepository = null;

    @Autowired
    private final SlotRepository slotRepository = null;

    @GetMapping("slots/")
    public String accountingWarehouseSlots(
            Model model,
            HttpServletRequest request
    ) {

        // Doing this in a single would be hard and error prone.
        // Writing native queries should be minimized.
        // Therefore this method was prefered
        List<WarehouseBookingPositionSlotEntry> entries = slotRepository.findAll().stream().map(
                s -> warehouseBookingPositionSlotEntryRepository
                        .getBySlotNum(s.slotNum)
                        .orElseGet(() -> WarehouseBookingPositionSlotEntry.empty(null, s))
        ).collect(Collectors.toList());
        model.addAttribute("entries", entries);

        model.addAttribute("stats", new CalculateWarehouseStatsAction(entries).finish());
        return "intern/warehouse/slots/index";
    }
}
