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.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 PDFResponseEntityInputStreamResource pdfGenerator;

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

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

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

        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 pdf
        return pdfGenerator.generatePdf( htmlStr, "Po-status", "inline" );
    }

}
