import { Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put, QueryParam } from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { getConnectionManager, Repository } from 'typeorm';
import { EntityFromBody } from 'typeorm-routing-controllers-extensions';
import { UserGroupIdsNotMatchingError, UserGroupNotFoundError } from '../errors/UserGroupErrors';
import { CreateUserGroup } from '../models/actions/CreateUserGroup';
import { UserGroup } from '../models/entities/UserGroup';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseUserGroup } from '../models/responses/ResponseUserGroup';
import { PermissionController } from './PermissionController';


@JsonController('/usergroups')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class UserGroupController {
	private userGroupsRepository: Repository<UserGroup>;

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

	@Get()
	@Authorized("USERGROUP:GET")
	@ResponseSchema(UserGroup, { isArray: true })
	@OpenAPI({ description: 'Lists all groups. <br> The information provided might change while the project continues to evolve.' })
	getAll() {
		return this.userGroupsRepository.find({ relations: ["permissions"] });
	}

	@Get('/:id')
	@Authorized("USERGROUP:GET")
	@ResponseSchema(UserGroup)
	@ResponseSchema(UserGroupNotFoundError, { statusCode: 404 })
	@OnUndefined(UserGroupNotFoundError)
	@OpenAPI({ description: 'Lists all information about the group whose id got provided. <br> The information provided might change while the project continues to evolve.' })
	getOne(@Param('id') id: number) {
		return this.userGroupsRepository.findOne({ id: id }, { relations: ["permissions"] });
	}

	@Post()
	@Authorized("USERGROUP:CREATE")
	@ResponseSchema(UserGroup)
	@ResponseSchema(UserGroupNotFoundError)
	@OpenAPI({ description: 'Create a new group. <br> If you want to grant permissions to the group you have to create them seperately by posting to /api/permissions after creating the group.' })
	async post(@Body({ validate: true }) createUserGroup: CreateUserGroup) {
		let userGroup;
		try {
			userGroup = await createUserGroup.toUserGroup();
		} catch (error) {
			throw error;
		}

		return this.userGroupsRepository.save(userGroup);
	}

	@Put('/:id')
	@Authorized("USERGROUP:UPDATE")
	@ResponseSchema(UserGroup)
	@ResponseSchema(UserGroupNotFoundError, { statusCode: 404 })
	@ResponseSchema(UserGroupIdsNotMatchingError, { statusCode: 406 })
	@OpenAPI({ description: "Update the group whose id you provided. <br> To change the permissions granted to the group please use /api/permissions instead. <br> Please remember that ids can't be changed." })
	async put(@Param('id') id: number, @EntityFromBody() userGroup: UserGroup) {
		let oldUserGroup = await this.userGroupsRepository.findOne({ id: id }, { relations: ["permissions"] });

		if (!oldUserGroup) {
			throw new UserGroupNotFoundError()
		}

		if (oldUserGroup.id != userGroup.id) {
			throw new UserGroupIdsNotMatchingError();
		}

		await this.userGroupsRepository.save(userGroup);
		return userGroup;
	}

	@Delete('/:id')
	@Authorized("USERGROUP:DELETE")
	@ResponseSchema(ResponseUserGroup)
	@ResponseSchema(ResponseEmpty, { statusCode: 204 })
	@OnUndefined(204)
	@OpenAPI({ description: 'Delete the group whose id you provided. <br> If there are any permissions directly granted to the group they will get deleted as well. <br> Users associated with this group won\'t get deleted - just deassociated. <br> If no group with this id exists it will just return 204(no content).' })
	async remove(@Param("id") id: number, @QueryParam("force") force: boolean) {
		let group = await this.userGroupsRepository.findOne({ id: id }, { relations: ["permissions"] });
		if (!group) { return null; }
		const responseGroup = await this.userGroupsRepository.findOne({ id: id }, { relations: ['permissions'] });

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

		await this.userGroupsRepository.delete(group);
		return new ResponseUserGroup(responseGroup);
	}
}
