package com.utopiaindustries.controller;

import com.utopiaindustries.auth.CuttingRole;
import com.utopiaindustries.auth.ReportingRole;
import com.utopiaindustries.model.ctp.SummaryInventoryReport;
import com.utopiaindustries.service.SummaryInventoryReportService;
import com.utopiaindustries.util.StringUtils;
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 org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@ReportingRole
@RequestMapping( "/reporting" )
public class ReportingController {
    private final SummaryInventoryReportService summaryInventoryReportService;

    public ReportingController(SummaryInventoryReportService summaryInventoryReportService2) {
        this.summaryInventoryReportService = summaryInventoryReportService2;
    }

    @GetMapping( "/summary")
    public String showMasterBundles(@RequestParam(value = "item-id", required = false ) String itemId, @RequestParam(value = "sku" , required = false) String sku, @RequestParam(value = "start-date", required = false) String startDate, @RequestParam(value = "end-date", required = false) String endDate, Model model ){

        LocalDate startDate1 = StringUtils.isNullOrEmpty(startDate) ? LocalDate.now().minusDays(6) : LocalDate.parse(startDate);
        LocalDate endDate1 = StringUtils.isNullOrEmpty(endDate) ? LocalDate.now().plusDays(1) : LocalDate.parse(endDate);
        model.addAttribute("startDate", startDate1);
        model.addAttribute("endDate", endDate1);
        Map<String, Map<String, List<SummaryInventoryReport>>> getDataByFilteration = summaryInventoryReportService.findByFilter(itemId,sku,startDate,endDate);
        ArrayList<LocalDate> arrayList = generateDateList(startDate1,endDate1);
        model.addAttribute("dateLimits", arrayList);
        model.addAttribute("tableData", getDataByFilteration);
        return "/reporting/inventory-summary";
    }

    private ArrayList<LocalDate> generateDateList(LocalDate start, LocalDate end) {
        ArrayList<LocalDate> localDates = new ArrayList<>();
        while (start.isBefore(end)) {
            localDates.add(start);
            start = start.plusDays(1);
        }
        return localDates;
    }
}
