package eu.eudat.controllers;

import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.userguide.UserGuide;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@CrossOrigin
@RequestMapping(value = {"/api/userguide/"})
public class UserGuideController {

	private Environment environment;

	@Autowired
	public UserGuideController(Environment environment) {
		this.environment = environment;
	}

	@RequestMapping(path = "current", method = RequestMethod.GET )
	public ResponseEntity getUserGuide() throws IOException {
		Stream<Path> walk = Files.walk(Paths.get(this.environment.getProperty("userguide.path")));
		List<String> result = walk.filter(Files::isRegularFile)
								  .map(Path::toString).collect(Collectors.toList());

		String fileName =  result.get(0);
		InputStream is = new FileInputStream(fileName);

		String[] filepath = fileName.split("\\.")[0].split("\\\\");
		String simplename = filepath[filepath.length - 1];

		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setContentLength(is.available());
		responseHeaders.setContentType(MediaType.TEXT_HTML);
		responseHeaders.set("Content-Disposition", "attachment;filename=" + simplename);
		responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
		responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");

		byte[] content = new byte[is.available()];
		is.read(content);
		is.close();

		return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK);

	}

	@RequestMapping(value = "current", method = RequestMethod.POST)
	public @ResponseBody
	ResponseEntity<ResponseItem<String>> updateGuide(@RequestBody UserGuide guide) throws Exception {
		String fileName =  this.environment.getProperty("userguide.path") + guide.getName() + ".html";
		OutputStream os = new FileOutputStream(fileName);
		os.write(guide.getHtml().getBytes());
		os.close();
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated").payload("Updated"));
	}
}
