package com.utopiaindustries.service;

import com.utopiaindustries.dao.ctp.StoreItemDao;
import com.utopiaindustries.dao.uind.PurchaseOrderDAO;
import com.utopiaindustries.model.ctp.JobCardItem;
import com.utopiaindustries.model.ctp.POsDetails;
import com.utopiaindustries.model.uind.PurchaseOrder;
import com.utopiaindustries.util.HTMLBuilder;
import com.utopiaindustries.util.PDFResponseEntityInputStreamResource;
import com.utopiaindustries.util.URLUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PurchaseOrderService {

    private final PurchaseOrderDAO purchaseOrderDAO;
    private final PurchaseOrderCTPService purchaseOrderCTPService;
    private final HTMLBuilder htmlBuilder;
    private final PDFResponseEntityInputStreamResource pdfGenerator;
    private final ReportingService reportingService;

    public PurchaseOrderService(PurchaseOrderDAO purchaseOrderDAO, PurchaseOrderCTPService purchaseOrderCTPService, HTMLBuilder htmlBuilder, PDFResponseEntityInputStreamResource pdfGenerator, ReportingService reportingService) {
        this.purchaseOrderDAO = purchaseOrderDAO;
        this.purchaseOrderCTPService = purchaseOrderCTPService;
        this.htmlBuilder = htmlBuilder;
        this.pdfGenerator = pdfGenerator;
        this.reportingService = reportingService;
    }

    public List<PurchaseOrder> findByTerm( String term ){
        return purchaseOrderDAO.findByTerm( term );
    }

    /**
     * Print po pdf *
     * **/
    public ResponseEntity<InputStreamResource> generatePOPdf(POsDetails pOsDetails, Model model, boolean includeItemsDetail, boolean storeDetail, String size, String color ) throws Exception {
        Map<String,Integer> storeItems = purchaseOrderCTPService.getStoreItemsByPoId(pOsDetails.getPoId());
        model.addAttribute("poDetail",  pOsDetails);
        model.addAttribute( "baseUrl", URLUtils.getCurrentBaseUrl() );

        model.addAttribute("date", LocalDateTime.now());
        if (includeItemsDetail){
            model.addAttribute("showItems", true);
            model.addAttribute("poItems", reportingService.getPoItemsSizeOrColor(pOsDetails.getPoId(), size, color));
        }else {
            model.addAttribute("showItems", false);
        }

        if (storeDetail && !storeItems.isEmpty()){
            model.addAttribute("showStore", true);
            model.addAttribute("store", storeItems);
        }else {
            model.addAttribute("showStore", false);
        }

        String htmlStr = htmlBuilder.buildHTML( "po-status-pdf", model );
        return pdfGenerator.generatePdf( htmlStr, "Po-status", "inline" );
    }

}
