import { Body, CurrentUser, Delete, Get, JsonController, OnUndefined, Put, QueryParam } from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { getConnectionManager, Repository } from 'typeorm';
import { PasswordMustContainLowercaseLetterError, PasswordMustContainNumberError, PasswordMustContainUppercaseLetterError, PasswordTooShortError, UserDeletionNotConfirmedError, UserIdsNotMatchingError, UsernameContainsIllegalCharacterError, UserNotFoundError } from '../errors/UserErrors';
import { UpdateUser } from '../models/actions/update/UpdateUser';
import { User } from '../models/entities/User';
import { ResponseUser } from '../models/responses/ResponseUser';
import { ResponseUserPermissions } from '../models/responses/ResponseUserPermissions';
import { PermissionController } from './PermissionController';


@JsonController('/users/me')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class MeController {
	private userRepository: Repository<User>;

	/**
	 * Gets the repository of this controller's model/entity.
	 */
	constructor() {
		this.userRepository = getConnectionManager().get().getRepository(User);
	}

	@Get('/')
	@ResponseSchema(ResponseUser)
	@ResponseSchema(UserNotFoundError, { statusCode: 404 })
	@OnUndefined(UserNotFoundError)
	@OpenAPI({ description: 'Lists all information about yourself.' })
	async get(@CurrentUser() currentUser: User) {
		let user = await this.userRepository.findOne({ id: currentUser.id }, { relations: ['permissions', 'groups', 'groups.permissions', 'permissions.principal', 'groups.permissions.principal'] })
		if (!user) { throw new UserNotFoundError(); }
		return new ResponseUser(user);
	}

	@Get('/permissions')
	@ResponseSchema(ResponseUserPermissions)
	@ResponseSchema(UserNotFoundError, { statusCode: 404 })
	@OnUndefined(UserNotFoundError)
	@OpenAPI({ description: 'Lists all permissions granted to the you sorted into directly granted and inherited as permission response objects.' })
	async getPermissions(@CurrentUser() currentUser: User) {
		let user = await this.userRepository.findOne({ id: currentUser.id }, { relations: ['permissions', 'groups', 'groups.permissions', 'permissions.principal', 'groups.permissions.principal'] })
		if (!user) { throw new UserNotFoundError(); }
		return new ResponseUserPermissions(user);
	}

	@Put('/')
	@ResponseSchema(ResponseUser)
	@ResponseSchema(UserNotFoundError, { statusCode: 404 })
	@ResponseSchema(UserIdsNotMatchingError, { statusCode: 406 })
	@ResponseSchema(UsernameContainsIllegalCharacterError, { statusCode: 406 })
	@ResponseSchema(PasswordMustContainUppercaseLetterError, { statusCode: 406 })
	@ResponseSchema(PasswordMustContainLowercaseLetterError, { statusCode: 406 })
	@ResponseSchema(PasswordMustContainNumberError, { statusCode: 406 })
	@ResponseSchema(PasswordTooShortError, { statusCode: 406 })
	@OpenAPI({ description: "Update the yourself. <br> You can't edit your own permissions or group memberships here - Please use the /api/users/:id enpoint instead. <br> Please remember that ids can't be changed." })
	async put(@CurrentUser() currentUser: User, @Body({ validate: true }) updateUser: UpdateUser) {
		let oldUser = await this.userRepository.findOne({ id: currentUser.id }, { relations: ['groups'] });
		updateUser.groups = oldUser.groups.map(g => g.id);

		if (!oldUser) {
			throw new UserNotFoundError();
		}

		if (oldUser.id != updateUser.id) {
			throw new UserIdsNotMatchingError();
		}
		await this.userRepository.save(await updateUser.update(oldUser));

		return new ResponseUser(await this.userRepository.findOne({ id: currentUser.id }, { relations: ['permissions', 'groups', 'groups.permissions'] }));
	}

	@Delete('/')
	@ResponseSchema(ResponseUser)
	@ResponseSchema(UserNotFoundError, { statusCode: 404 })
	@ResponseSchema(UserDeletionNotConfirmedError, { statusCode: 406 })
	@OpenAPI({ description: 'Delete yourself. <br> You have to confirm your decision by providing the ?force=true query param. <br> If there are any permissions directly granted to you they will get deleted as well.' })
	async remove(@CurrentUser() currentUser: User, @QueryParam("force") force: boolean) {
		if (!force) { throw new UserDeletionNotConfirmedError; }
		if (!currentUser) { return UserNotFoundError; }
		const responseUser = await this.userRepository.findOne({ id: currentUser.id }, { relations: ['permissions', 'groups', 'groups.permissions'] });;

		const permissionControler = new PermissionController();
		for (let permission of responseUser.permissions) {
			await permissionControler.remove(permission.id, true);
		}

		await this.userRepository.delete(currentUser);
		return new ResponseUser(responseUser);
	}
}