package de.champonthis.buntspecht.i18n.controller;

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

import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;

import de.champonthis.buntspecht.controller.BaseController;
import de.champonthis.buntspecht.i18n.businesslogic.I18nManager;


@RestController
@RequestMapping("/i18n")
public class I18nController extends BaseController {

	@Autowired
	private I18nManager i18nManager;

	private Gson gson = new Gson();

	
	@GetMapping
	public List<String> getLocales() {
		return i18nManager.getLocales();
	}

	
	@GetMapping("/{locale}")
	public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response)
			throws JsonIOException, IOException {
		JsonObject label = i18nManager.getLabel(locale);
		if (label != null) {
			response.setCharacterEncoding("utf-8");
			gson.toJson(label, response.getWriter());
		}
	}

	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@PostMapping("/{locale}")
	public void setLabel(@PathVariable("locale") String locale, @RequestBody Object label) {
		JsonElement element = gson.toJsonTree(label);

		if (element != null && element.isJsonObject()) {
			i18nManager.setLabel(locale, element.getAsJsonObject());
		}
	}

	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@PutMapping("/{locale}")
	public void addLabel(@PathVariable("locale") String locale, @RequestBody Object label) {
		JsonElement element = gson.toJsonTree(label);

		if (element != null && element.isJsonObject()) {
			i18nManager.addLabel(locale, element.getAsJsonObject());
		}
	}

	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@DeleteMapping("/{locale}")
	public void deleteLocale(@PathVariable("locale") String locale) {
		i18nManager.deleteLabel(locale);
	}

}
