package com.utopiaindustries.controller;

import com.utopiaindustries.auth.PurchaseOrderCTPRole;
import com.utopiaindustries.model.ctp.JobCard;
import com.utopiaindustries.service.PurchaseOrderCTPService;
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.List;

@Controller
@RequestMapping("/purchase-order")
@PurchaseOrderCTPRole

public class PurchaseOrderCTPController {
    private final PurchaseOrderCTPService purchaseOrderCTPService;

    public PurchaseOrderCTPController(PurchaseOrderCTPService purchaseOrderCTPService) {
        this.purchaseOrderCTPService = purchaseOrderCTPService;
    }

    @GetMapping
    public String showJobCardList(  @RequestParam( value = "purchaseOrderCode", required = false ) String purchaseOrderCode,
                                    @RequestParam( value = "articleName", required = false ) String articleName,
                                    @RequestParam( value = "created-start-date", required = false ) String createdStartDate,
                                    @RequestParam( value = "created-end-date", required = false ) String createdEndDate,
                                    @RequestParam( value = "limit" , required = false) Long limit,
                                    Model model ){

        LocalDate startDate = StringUtils.isNullOrEmpty(createdStartDate) ? LocalDate.now().minusDays(30) : LocalDate.parse(createdStartDate);
        LocalDate endDate = StringUtils.isNullOrEmpty(createdEndDate) ? LocalDate.now() : LocalDate.parse(createdEndDate);
        model.addAttribute("purchaseOrder", purchaseOrderCTPService.getAllPurchaseOrderCtp(purchaseOrderCode, articleName, startDate.toString(), endDate.toString(), limit) );
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        return "job-card-list";
    }

    @GetMapping( "/new" )
    public String showPurchaseOrderCTPForm( Model model ){
        model.addAttribute("purchaseOrder", purchaseOrderCTPService.createNewPurchaseOrderCTP() );
        return "/purchaseOrder/purchase-order-form";
    }
}
