package gov.va.vinci.dart.jobs.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import gov.va.vinci.dart.biz.Participant;
import gov.va.vinci.dart.biz.Request;
import gov.va.vinci.dart.db.RequestDAO;
import gov.va.vinci.dart.jobs.PreparatoryDailyEmailsService;
import gov.va.vinci.dart.wf2.EmailUtils;

/**
 * The Class PreparatoryDailyEmailsServiceImpl.  
 * 
 * Process method is called by a Quartz trigger found in quartz-process.xml file
 */
@Service
public final class PreparatoryDailyEmailsServiceImpl implements PreparatoryDailyEmailsService, InitializingBean {

    /** Spring Injected RequestDAO. */
    @Resource
    private RequestDAO requestDAO;
    
    /** The Constant LOG. */
    private static final Logger LOG = LogManager.getLogger(PreparatoryDailyEmailsServiceImpl.class);

    @Override
    @Transactional
    public void process() {

        List<Request> requests = null;
        Date today = getSearchableDate();
        requests = requestDAO.findExpectedIRBSubmissionByDate(today);

        if (requests != null) {

            for (Request request : requests) {
                EmailUtils.sendExpectedIRBSubmissionDateHasExpiredEmail(request);

            }
        } else {
            LOG.info("No Requests found with expiring Expected IRB submission date ");
        }
    }



    /**
     * Gets the searchable date. Today's date is used.
     * 
     * Format of the date originally came from the data picker in the javascript.
     *
     * @return the searchable date
     */
    private Date getSearchableDate() {
        Date today = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            today = dateFormat.parse(dateFormat.format(new Date()));
        } catch (ParseException e) {
            LOG.error("Failed to parse new date in method getSearchableDate.");
            e.printStackTrace();
        }
        return today;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (requestDAO == null) {
            throw new Exception("RequestDAO has not been injected in to PreparatoryDailyEmailsServiceImpl.");
        }
    }
}
