package dk.statsbiblioteket.newspaper.processmonitor.backend;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import dk.statsbiblioteket.newspaper.mfpakintegration.database.InconsistentDatabaseException;
import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO;

@Component
public class MfPakBatchEnricher implements BatchEnricher {

    private MfPakDAO mfpak;
    private Logger log = LoggerFactory.getLogger(getClass());
    public MfPakDAO getMfpak() {
        return mfpak;
    }

    public void setMfpak(MfPakDAO mfpak) {
        this.mfpak = mfpak;
    }
    
    /**
     * Enriches the batch objects with 'avisid' and date intervals from the mfpak database. 
     * The returned reference to list of batches is the same as the one taken as input. 
     */
    @Override
    public List<Batch> enrich(List<Batch> batches) {
        
        for(Batch b : batches) {
            String batchID = b.getBatchID();
            try {
                b.setAvisID(mfpak.getNewspaperID(batchID));    
            } catch (InconsistentDatabaseException | SQLException e) {
                log.debug("Failed to enrich batch {}", batchID, e);
            }
                
        }
        
        return batches;
    }
    
}

@@ -82,24 +82,47 @@
 LException;%0A
+import java.util.Date;%0A
 import java.
@@ -132,16 +132,16 @@
 l.List;%0A
-
 %0Aimport 
@@ -494,16 +494,99 @@
 fPakDAO;
+%0Aimport dk.statsbiblioteket.newspaper.mfpakintegration.database.NewspaperDateRange;
 %0A%0A@Compo
@@ -1315,18 +1315,56 @@
 hID));  
+%0A
   
+              enrichWithDateRange(b);
 %0A       
@@ -1575,15 +1575,795 @@
 ;%0A    %7D%0A
-
     %0A
+    /**%0A     * Enriches the batch with the start and stop dates from mfpak %0A     */%0A    private Batch enrichWithDateRange(Batch batch) throws SQLException %7B%0A        List%3CNewspaperDateRange%3E ranges = mfpak.getBatchDateRanges(batch.getBatchID());%0A        Date tempStartDate = new Date();%0A        Date tempEndDate = new Date(0);%0A        %0A        for(NewspaperDateRange range : ranges) %7B%0A            if(range.getFromDate().before(tempStartDate)) %7B%0A                tempStartDate = range.getFromDate();%0A            %7D%0A            %0A            if(range.getToDate().after(tempEndDate)) %7B%0A                tempEndDate = range.getToDate();%0A            %7D%0A        %7D%0A        %0A        batch.setStartDate(tempStartDate);%0A        batch.setEndDate(tempEndDate);%0A        %0A        return batch;%0A    %7D%0A
 %7D%0A

add initial, perhaps naive, enrichment of web-batch dates