import { Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put, QueryParam } from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { Repository, getConnection, getConnectionManager } from 'typeorm';
import { GroupContactIdsNotMatchingError, GroupContactNotFoundError } from '../errors/GroupContactErrors';
import { RunnerGroupNotFoundError } from '../errors/RunnerGroupErrors';
import { CreateGroupContact } from '../models/actions/create/CreateGroupContact';
import { UpdateGroupContact } from '../models/actions/update/UpdateGroupContact';
import { GroupContact } from '../models/entities/GroupContact';
import { RunnerGroup } from '../models/entities/RunnerGroup';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseGroupContact } from '../models/responses/ResponseGroupContact';

@JsonController('/contacts')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class GroupContactController {
	private contactRepository: Repository<GroupContact>;

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

	@Get()
	@Authorized("CONTACT:GET")
	@ResponseSchema(ResponseGroupContact, { isArray: true })
	@OpenAPI({ description: 'Lists all contacts. <br> This includes the contact\'s associated groups.' })
	async getAll(@QueryParam("page", { required: false }) page: number, @QueryParam("page_size", { required: false }) page_size: number = 100) {
		let responseContacts: ResponseGroupContact[] = new Array<ResponseGroupContact>();
		let contacts: Array<GroupContact>;

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

		contacts.forEach(contact => {
			responseContacts.push(contact.toResponse());
		});
		return responseContacts;
	}

	@Get('/:id')
	@Authorized("CONTACT:GET")
	@ResponseSchema(ResponseGroupContact)
	@ResponseSchema(GroupContactNotFoundError, { statusCode: 404 })
	@OnUndefined(GroupContactNotFoundError)
	@OpenAPI({ description: 'Lists all information about the contact whose id got provided. <br> This includes the contact\'s associated groups.' })
	async getOne(@Param('id') id: number) {
		let contact = await this.contactRepository.findOne({ id: id }, { relations: ['groups', 'groups.parentGroup'] })
		if (!contact) { throw new GroupContactNotFoundError(); }
		return contact.toResponse();
	}

	@Post()
	@Authorized("CONTACT:CREATE")
	@ResponseSchema(ResponseGroupContact)
	@ResponseSchema(RunnerGroupNotFoundError, { statusCode: 404 })
	@OpenAPI({ description: 'Create a new contact.' })
	async post(@Body({ validate: true }) createContact: CreateGroupContact) {
		let contact;
		try {
			contact = await createContact.toEntity();
		} catch (error) {
			throw error;
		}

		contact = await this.contactRepository.save(contact)
		return (await this.contactRepository.findOne({ id: contact.id }, { relations: ['groups', 'groups.parentGroup'] })).toResponse();
	}

	@Put('/:id')
	@Authorized("CONTACT:UPDATE")
	@ResponseSchema(ResponseGroupContact)
	@ResponseSchema(GroupContactNotFoundError, { statusCode: 404 })
	@ResponseSchema(GroupContactIdsNotMatchingError, { statusCode: 406 })
	@ResponseSchema(RunnerGroupNotFoundError, { statusCode: 404 })
	@OpenAPI({ description: "Update the contact whose id you provided. <br> Please remember that ids can't be changed." })
	async put(@Param('id') id: number, @Body({ validate: true }) contact: UpdateGroupContact) {
		let oldContact = await this.contactRepository.findOne({ id: id });

		if (!oldContact) {
			throw new GroupContactNotFoundError();
		}

		if (oldContact.id != contact.id) {
			throw new GroupContactIdsNotMatchingError();
		}

		await this.contactRepository.save(await contact.update(oldContact));
		return (await this.contactRepository.findOne({ id: contact.id }, { relations: ['groups', 'groups.parentGroup'] })).toResponse();
	}

	@Delete('/:id')
	@Authorized("CONTACT:DELETE")
	@ResponseSchema(ResponseGroupContact)
	@ResponseSchema(ResponseEmpty, { statusCode: 204 })
	@OnUndefined(204)
	@OpenAPI({ description: 'Delete the contact whose id you provided. <br> If no contact with this id exists it will just return 204(no content). <br> This won\'t delete any groups associated with the contact.' })
	async remove(@Param("id") id: number, @QueryParam("force") force: boolean) {
		let contact = await this.contactRepository.findOne({ id: id });
		if (!contact) { return null; }
		const responseContact = await this.contactRepository.findOne(contact, { relations: ['groups', 'groups.parentGroup'] });
		for (let group of responseContact.groups) {
			group.contact = null;
			await getConnection().getRepository(RunnerGroup).save(group);
		}

		await this.contactRepository.delete(contact);
		return responseContact.toResponse();
	}
}
