package es.uv.saic.domain;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import jakarta.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import es.uv.saic.service.CalendariService;
import es.uv.saic.service.EmailService;
import es.uv.saic.service.InstanciaService;
import es.uv.saic.service.InstanciaTascaService;
import es.uv.saic.service.ParserService;
import es.uv.saic.service.SysStatusService;
import es.uv.saic.service.UsuariService;

@Component
@SuppressWarnings("unused")
public class ScheduledTasks {
	
	@Autowired
	private EmailService es;
	@Autowired
	private InstanciaService it;
	@Autowired
	private InstanciaTascaService its;
	@Autowired
	private UsuariService us;
	@Autowired
	private ParserService ps;
	@Autowired
	private CalendariService cs;
	@Autowired
	private SysStatusService sss;
	@Value("${saic.mailer.queue.enabled}")
	private String queueEnabled;
	@Value("${saic.mailer.reminder.enabled}")
	private String reminderEnabled;
	@Value("${saic.mailer.calendar.enabled}")
	private String calendarEnabled;
	@Value("${saic.mailer.maxMailsPerRound}")
	private Integer maxMailsPerRound;
	@Value("${saic.parser.surveys.enabled}")
	private String parserEnabled;
	@Value("${saic.scheduler.expired.enabled}")
	private String expiredEnabled;

	@Scheduled(fixedDelay = 300000)
	public void sendInstanceMails() {
		if(Boolean.parseBoolean(this.queueEnabled)) {
			Integer counter = 0;
			while(!es.pendingQueueIsEmpty() && counter < maxMailsPerRound) {
				es.sendActiveTaskNext();
				counter+=1;
			}
		}
	}
	
	@Scheduled(cron="0 0 1 * * *")
	public void sendReminderMails() {
		if(Boolean.parseBoolean(this.reminderEnabled)) {
			sss.log("Start sending mail reminders");
			for(InstanciaTasca instanciaTasca : its.getPastTasks()) {
				for(Usuari u : us.getInstanceAsignedUsers(instanciaTasca.getInstancia().getIdInstancia())) {
					Email email = new Email();
					email.setUsusari(u);
					email.setInstanciaTasca(instanciaTasca);
					es.addEmail(email);
				}
			}
		}
	}
	
	@Scheduled(cron="0 0 1 * * *")
	public void sendCalendarMails() throws MessagingException {
		if(Boolean.parseBoolean(this.calendarEnabled)) {
			Integer counter = 0;
			Usuari u = this.us.findByUsername("system");
			List<Calendari> events = this.cs.getNextEvents();
			for(Calendari e : events) {
				this.es.sendCalendarMail(u, e);
				counter+=1;
			}
		}
	}
	
	@Scheduled(cron="0 0 1 * * *")
	public void closeExpiredTasks() {
		if(Boolean.parseBoolean(this.expiredEnabled)) {
			// to do in future
		}
	}

}
