package de.jottyfan.camporganizer.module.document;

import java.util.Base64;

import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import de.jottyfan.camporganizer.module.camplist.CommonController;

/**
 *
 * @author jotty
 *
 */
@RestController
public class DocumentController extends CommonController {

	@Autowired
	private DocumentService service;

	@GetMapping("/document/{id}")
	public ResponseEntity<Resource> getDocument(@PathVariable("id") Integer id, HttpServletResponse response) {
		DownloadBean bean = service.getDocument(id);
		if (bean != null) {
			byte[] decoded = Base64.getDecoder().decode(bean.getContent());
			HttpHeaders header = new HttpHeaders();
			header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + bean.getName() + "." + bean.getFiletype());
			MediaType contentType = MediaType.parseMediaType("application/octet-stream");
			Integer length = decoded.length;
			ByteArrayResource resource = new ByteArrayResource(decoded);
			return ResponseEntity.ok().headers(header).contentLength(length).contentType(contentType).body(resource);
		} else {
			return ResponseEntity.notFound().build();
		}
	}
}
