package eu.eudat.controllers;

import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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.util.UUID;

@RestController
@CrossOrigin
@RequestMapping(value = {"/api/language/"})
public class LanguageController {

	private Environment environment;

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

	@RequestMapping(value = "{lang}", method = RequestMethod.GET)
	public ResponseEntity getLanguage(@PathVariable String lang) throws IOException {

		String fileName =  this.environment.getProperty("language.path") + lang + ".json";
		InputStream is = new FileInputStream(fileName);

		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setContentLength(is.available());
		responseHeaders.setContentType(MediaType.APPLICATION_JSON);
		responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName);
		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 = "update/{lang}", method = RequestMethod.POST)
	public @ResponseBody
	ResponseEntity<ResponseItem<String>> updateLang(@PathVariable String lang, @RequestBody String json) throws Exception {
		String fileName =  this.environment.getProperty("language.path") + lang + ".json";
		OutputStream os = new FileOutputStream(fileName);
		os.write(json.getBytes());
		os.close();
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated").payload("Updated"));
	}
}
