package eu.eudat.controllers;

import eu.eudat.logic.managers.MetricsManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userguide.UserGuide;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.MetricNames;
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.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static eu.eudat.types.Authorities.ADMIN;

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

	private Environment environment;
	private final MetricsManager metricsManager;

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

	@RequestMapping(path = "{lang}", method = RequestMethod.GET )
	public ResponseEntity getUserGuide(@PathVariable(name = "lang") String lang) throws IOException {
		long files = 0;
		try (Stream<Path> paths = Files.list(Paths.get(Objects.requireNonNull(this.environment.getProperty("userguide.path"))))) {
			files = paths.count();
		}
			metricsManager.calculateValue(MetricNames.LANGUAGES, (int) files, null);
		try (Stream<Path> paths = Files.walk(Paths.get(Objects.requireNonNull(this.environment.getProperty("userguide.path"))))) {
			List<String> result = paths.filter(Files::isRegularFile)
					.map(Path::toString).collect(Collectors.toList());

			String fileName = result.stream().filter(guide -> guide.contains("_" + lang)).findFirst().orElse(null);
			if (fileName == null) {
				fileName = result.stream().filter(guide -> guide.contains("_en")).findFirst().get();
			}
			InputStream is = new FileInputStream(fileName);

			Path path = Paths.get(fileName);

			HttpHeaders responseHeaders = new HttpHeaders();
			responseHeaders.setContentLength(is.available());
			responseHeaders.setContentType(MediaType.TEXT_HTML);
			responseHeaders.set("Content-Disposition", "attachment;filename=" + path.getFileName().toString());
			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, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
		String fileName =  this.environment.getProperty("userguide.path") + guide.getName();
		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"));
	}
}
