package es.uv.saic.web;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import es.uv.saic.domain.Plantilla;
import es.uv.saic.dto.PdfDTO;
import es.uv.saic.dto.TemplateDataDTO;
import es.uv.saic.service.PlantillaService;


@RestController
public class PlantillaController {
    @Autowired
    private PlantillaService ps;

    @GetMapping("/plantilla")
    public List<Plantilla> findAll() {
        return ps.findAll();
    }

    @GetMapping("/plantilla/{id}")
    public Plantilla findByID(@PathVariable Integer id) {
        return ps.findByID(id);
    }
    
    @GetMapping("/plantilla/{versio}/{codi}/{ambit}")
    public Plantilla findByVersioCodiAmbit(@PathVariable Integer versio,
        @PathVariable String codi,
        @PathVariable String ambit) {
        try {
            Plantilla plantilla = ps.findByVersioCodiAmbit(versio, codi, ambit);

             return plantilla ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/plantilla/save")
    public String save(@RequestBody Plantilla plantilla) {
        try {
            ps.save(plantilla);
            return "Save";
        } catch (Exception e) {
            e.printStackTrace();
            return "Error guardando la plantilla: " + e.getMessage();
        }
    }
    
    @DeleteMapping("/plantilla/delete")
    public String delete(@RequestBody Plantilla plantilla) {
        ps.delete(plantilla);
        return "Delete";
    }
    
    @GetMapping("/plantilla/used/{id}")
    public boolean isUsed(@PathVariable Integer id) {
       return ps.isUsed(id);
    }

    @PostMapping("/addTemplateData")
    public String addTemplateData(@RequestBody TemplateDataDTO td) {
        return ps.addTemplateData(td.getInstanciaTasca(), td.getTemplate());
    }
    
    @PostMapping("/addTemplateData2")
    public String addTemplateData2(@RequestBody TemplateDataDTO td) {
        return ps.addTemplateData(td.getIdTitulacio(), td.getIdCentre(), td.getCurs(), td.getTemplate());        
}

    @PostMapping("/savePDF")
    public String savePDF(@RequestBody PdfDTO pdf) throws IOException, InterruptedException {
        return ps.savePDF(pdf.getContent(), pdf.getIdtasca());        

    }
    
}
