<?php

declare(strict_types=1);

final class UserPutController extends AbstractController
{
	protected string $route = '/api/v1/user/{userId}';

	private int $userId;

	public function __construct(string $url)
	{
		parent::__construct($url);

		$this->userId = (int)$this->getUrlParamInt('userId');
	}

	public function handle(): void
	{
		parent::handle();

		if ($this->response->getStatus() !== ServerStatus::OK) {
			return;
		}

		if ($this->requestBody === null) {
			$this->response = new ApiJsonResponse(ServerStatus::BAD_REQUEST);
			$this->response->setParameter('success', false);
			$this->response->setMessage('No JSON body with changed parametesrs found!');
		}

		try {
			$json = json_decode($this->requestBody, true);
			$user = new User($this->userId);

			$hasChanged = $this->handleUserData($user, $json);

			$this->response = new ApiJsonResponse();

			if ($hasChanged) {
				$user->Save();
				return;
			}

			$this->response->setMessage('No differing attributes found. Nothing changed.');
		} catch (Throwable $e) {
			$this->response = new ApiJsonResponse(ServerStatus::BAD_REQUEST);
			$this->response->setParameter('success', false);
			$this->response->setMessage($e->getMessage());
		}
	}

	private function setUsername(User $user, array $json): bool
	{
		if (isset($json['username'])) {
			$hasChanged = $user->getUsername() !== $json['username'];
			$user->setUsername($json['username']);

			return $hasChanged;
		}

		return false;
	}

	private function setPassword(User $user, array $json): bool
	{
		if (isset($json['password'])) {
			$hasChanged = !Password::IsValid($json['password'], $user->getPassword());

			$user->setPassword(Password::GetHash($json['password']));

			return $hasChanged;
		}

		return false;
	}


	private function setEmail(User $user, array $json): bool
	{
		if (isset($json['email'])) {
			$hasChanged = $user->getEmail() !== $json['email'];
			$user->setEmail($json['email']);

			return $hasChanged;
		}

		return false;
	}

	private function setJabberAddress(User $user, array $json): bool
	{
		if (isset($json['jabberAddress'])) {
			$hasChanged = $user->getJabberAddress() !== $json['jabberAddress'];
			$user->setJabberAddress($json['jabberAddress']);

			return $hasChanged;
		}

		return false;
	}

	private function handleUserData(User $user, array $json): bool
	{
		$hasChanged = $this->setUsername($user, $json) || false;
		$hasChanged = $this->setPassword($user, $json) || $hasChanged;
		$hasChanged = $this->setEmail($user, $json) || $hasChanged;
		$hasChanged = $this->setJabberAddress($user, $json) || $hasChanged;

		return $hasChanged;
	}
}