package es.uv.saic.service;

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

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import es.uv.saic.domain.Document;
import es.uv.saic.domain.DocumentRepository;

@Service
public class DocumentService {
	
	@Autowired
	private DocumentRepository dr;
	
	@Value("${saic.data.docsPath}")
	private String docsPath;

	
	public List<Document> getAll() {
		return this.dr.findAll();
	}
	
	public Document findById(Integer id) {
		Optional<Document> c = this.dr.findById(id);
		if(!c.isEmpty()) {
			return c.get();
		}
		return null;
	}
	
	public List<Document> findAllByCategoriaOrgan(Integer categoria, Integer lugar, String tlugar){
		return this.dr.findAllByCategoriaOrgan(categoria, lugar, tlugar);
	}
	
	public Document findByCategoriaOrgan(Integer categoria, Integer lugar, String tlugar){
		return this.dr.findByCategoriaOrgan(categoria, lugar, tlugar);
	}
	
	public List<Document> findByCategoriaNom(String nom){
		return this.dr.findByCategoriaNom(nom);
	}
	
	public List<Document> findByCategoriaTipus(String tipus){
		return this.dr.findByCategoriaTipus(tipus);
	}
	
	public Document archive(Document d) {
		d.setVisible(false);
		d = this.dr.save(d);
		return d;
	}
	
	public void archiveByOrgan(Integer lugar, String tlugar) {
		this.dr.archiveByOrgan(lugar, tlugar);
	}
	
	public boolean exists(Integer idCategoria, Integer lugar, String tlugar) {
		Document d = this.dr.findByCategoriaOrgan(idCategoria, lugar, tlugar);
		if(d == null) {
			return false;
		}
		return true;
	}
	
	public Document save(Document d) {
		return this.dr.saveAndFlush(d);
	}
	
	public void delete(Document d) {
		this.dr.delete(d);
	}
	
	public String upload(Integer idDocument, Integer idCategoria, Integer lugar, String tlugar, MultipartFile file) throws IllegalStateException, IOException {
		String ext = FilenameUtils.getExtension(file.getOriginalFilename());
		String fname = lugar.toString()+"_"+tlugar+"_"+idCategoria.toString()+"_"+idDocument.toString()+"."+ext;
		file.transferTo(new File(docsPath+fname));
		return docsPath+fname;
	}
}
