package es.uv.saic.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import es.uv.saic.domain.Instancia;
import es.uv.saic.domain.InstanciaTasca;
import es.uv.saic.dto.PdfDTO;
import es.uv.saic.feign.PlantillaClient;
import es.uv.saic.service.InstanciaService;
import es.uv.saic.service.InstanciaTascaService;

//	Generates PDFs for all instances of a given process and task for admin user 
@Controller
public class TestController {
		
	@Autowired 
	private InstanciaService ins;
	@Autowired 
	private InstanciaTascaService its;
	@Autowired
	private PlantillaClient plc;
	
	@Value("${saic.data.filePath}")
	private String filePath;
	@Value("${saic.data.templates.fileNotFound}")
	private String fileNotFound;
	@Value("${saic.data.templates.filePath}")
	private String templatePath;
	@Value("${saic.data.templates.logoPath}")
	private String logoPath;	
	
	/*
	 * Generates PDFs for all instances of a given process and task for admin user
	 * 
	 * @param auth The authentication object
	 * @return A string indicating the result of the operation
	 * @throws FileNotFoundException If a required file is not found
	 * @throws IOException If an I/O error occurs
	 * @throws InterruptedException If the thread is interrupted
	 */
	@GetMapping("/admin/pdf")
	@Secured({"ROLE_ADMIN"})
	@ResponseBody
	public String generatePDF(Authentication auth) throws FileNotFoundException, IOException, InterruptedException {
		
		// 94231 y 94232    tascap = 300
		List<Instancia> instancies = ins.findByIdProces(94231);
		for(Instancia i : instancies) {
			InstanciaTasca it = this.its.findByInstanciaTascap(i.getIdInstancia(), 300);
			if(it.getEstat() != null) {
				if(it.getEstat().equals("E")) {
					PdfDTO pdf = new PdfDTO(it.getText(), it.getIdInstanciaTasca());
					String dst = plc.savePDF(pdf);
					it.setEvidencia(dst);
					its.save(it);
				}
			}	
		}
		
		instancies = new ArrayList<Instancia>();
		instancies = ins.findByIdProces(94231);
		for(Instancia i : instancies) {
			InstanciaTasca it = this.its.findByInstanciaTascap(i.getIdInstancia(), 300);
			if(it.getEstat() != null) {
				if(it.getEstat().equals("E")) {
					PdfDTO pdf = new PdfDTO(it.getText(), it.getIdInstanciaTasca());
					String dst = plc.savePDF(pdf);
					it.setEvidencia(dst);
					its.save(it);
				}
			}	
		}
		
		return "OK";
	}
	
}
