/**
 * 
 */
package de.bstly.board.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import de.bstly.board.businesslogic.UserManager;
import de.bstly.board.controller.support.EntityResponseStatusException;
import de.bstly.board.model.LocalUser;


/**
 * The Class UserController.
 */
@RestController
@RequestMapping("/users")
public class UserController extends BaseController {

	
	@Autowired
	private UserManager userManager;

	/**
	 * Gets the user.
	 *
	 * @param usernameParameter the username parameter
	 * @return the user
	 */
	@PreAuthorize("isAuthenticated()")
	@GetMapping({ "/user", "/user/{username}" })
	public LocalUser getUser(@PathVariable("username") Optional<String> usernameParameter) {
		String username = usernameParameter.orElse(getCurrentUsername());

		LocalUser user = userManager.getByUsername(username);

		if (user == null) {
			throw new EntityResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY);
		}

		if (user.getUsername() != getCurrentUsername()) {
			LocalUser otherUser = new LocalUser();
			otherUser.setUsername(user.getUsername());
			otherUser.setAbout(user.getAbout());
		}

		user.setPasswordHash(null);

		userManager.applyMetadata(getCurrentUsername(), user);

		return user;
	}

	/**
	 * Update user.
	 *
	 * @param user the user
	 * @return the local user
	 */
	@PreAuthorize("isAuthenticated()")
	@PostMapping("/user")
	public LocalUser updateUser(@RequestBody LocalUser user) {
		if (!getCurrentUsername().equals(user.getUsername())) {
			throw new EntityResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY);
		}

		LocalUser orgUser = userManager.getByUsername(user.getUsername());

		orgUser.setAbout(user.getAbout());
		orgUser.setDarkTheme(user.isDarkTheme());
		orgUser.setEmail(user.getEmail());
		orgUser.setLocale(user.getLocale());
		orgUser.setSettings(user.getSettings());

		user = userManager.save(orgUser);

		user.setPasswordHash(null);

		userManager.applyMetadata(getCurrentUsername(), user);

		return user;
	}

}
