import { Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put, QueryParam } from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { Repository, getConnectionManager } from 'typeorm';
import { UserGroupIdsNotMatchingError, UserGroupNotFoundError } from '../errors/UserGroupErrors';
import { CreateUserGroup } from '../models/actions/create/CreateUserGroup';
import { UpdateUserGroup } from '../models/actions/update/UpdateUserGroup';
import { UserGroup } from '../models/entities/UserGroup';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseUserGroup } from '../models/responses/ResponseUserGroup';
import { ResponseUserGroupPermissions } from '../models/responses/ResponseUserGroupPermissions';
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(ResponseUserGroup, { isArray: true })
	@OpenAPI({ description: 'Lists all groups. <br> The information provided might change while the project continues to evolve.' })
	async getAll(@QueryParam("page", { required: false }) page: number, @QueryParam("page_size", { required: false }) page_size: number = 100) {
		let responseGroups: ResponseUserGroup[] = new Array<ResponseUserGroup>();
		let groups: Array<UserGroup>;

		if (page != undefined) {
			groups = await this.userGroupsRepository.find({ relations: ['permissions'], skip: page * page_size, take: page_size });
		} else {
			groups = await this.userGroupsRepository.find({ relations: ['permissions'] });
		}

		groups.forEach(group => {
			responseGroups.push(group.toResponse());
		});
		return responseGroups;
	}

	@Get('/:id')
	@Authorized("USERGROUP:GET")
	@ResponseSchema(ResponseUserGroup)
	@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.' })
	async getOne(@Param('id') id: number) {
		return await (await (this.userGroupsRepository.findOne({ id: id }, { relations: ["permissions"] }))).toResponse();
	}

	@Get('/:id/permissions')
	@Authorized("USERGROUP:GET")
	@ResponseSchema(ResponseUserGroupPermissions)
	@ResponseSchema(UserGroupNotFoundError, { statusCode: 404 })
	@OnUndefined(UserGroupNotFoundError)
	@OpenAPI({ description: 'Lists all permissions granted to the group as permission response objects.' })
	async getPermissions(@Param('id') id: number) {
		let group = await this.userGroupsRepository.findOne({ id: id }, { relations: ['permissions', 'permissions.principal'] })
		if (!group) { throw new UserGroupNotFoundError(); }
		return new ResponseUserGroupPermissions(group);
	}

	@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.toEntity();
		} catch (error) {
			throw error;
		}

		userGroup = await this.userGroupsRepository.save(userGroup);
		return (await (this.userGroupsRepository.findOne({ id: userGroup.id }, { relations: ["permissions"] }))).toResponse();
	}

	@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, @Body({ validate: true }) updateGroup: UpdateUserGroup) {
		let oldGroup = await this.userGroupsRepository.findOne({ id: id });

		if (!oldGroup) {
			throw new UserGroupNotFoundError();
		}

		if (oldGroup.id != updateGroup.id) {
			throw new UserGroupIdsNotMatchingError();
		}
		await this.userGroupsRepository.save(await updateGroup.update(oldGroup));

		return (await this.userGroupsRepository.findOne({ id: id }, { relations: ['permissions'] })).toResponse();
	}

	@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 });
		if (!group) { return null; }
		const responseGroup = await this.userGroupsRepository.findOne({ id: id }, { relations: ['permissions'] });

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

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