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 { RunnerOrganisationHasRunnersError, RunnerOrganisationHasTeamsError, RunnerOrganisationIdsNotMatchingError, RunnerOrganisationNotFoundError } from '../errors/RunnerOrganisationErrors';
import { CreateRunnerOrganisation } from '../models/actions/CreateRunnerOrganisation';
import { UpdateRunnerOrganisation } from '../models/actions/UpdateRunnerOrganisation';
import { RunnerOrganisation } from '../models/entities/RunnerOrganisation';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseRunnerOrganisation } from '../models/responses/ResponseRunnerOrganisation';
import { RunnerController } from './RunnerController';
import { RunnerTeamController } from './RunnerTeamController';


@JsonController('/organisations')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class RunnerOrganisationController {
	private runnerOrganisationRepository: Repository<RunnerOrganisation>;

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

	@Get()
	@Authorized("ORGANISATION:GET")
	@ResponseSchema(ResponseRunnerOrganisation, { isArray: true })
	@OpenAPI({ description: 'Lists all organisations. <br> This includes their address, contact and teams (if existing/associated).' })
	async getAll() {
		let responseTeams: ResponseRunnerOrganisation[] = new Array<ResponseRunnerOrganisation>();
		const runners = await this.runnerOrganisationRepository.find({ relations: ['address', 'contact', 'teams'] });
		runners.forEach(runner => {
			responseTeams.push(new ResponseRunnerOrganisation(runner));
		});
		return responseTeams;
	}

	@Get('/:id')
	@Authorized("ORGANISATION:GET")
	@ResponseSchema(ResponseRunnerOrganisation)
	@ResponseSchema(RunnerOrganisationNotFoundError, { statusCode: 404 })
	@OnUndefined(RunnerOrganisationNotFoundError)
	@OpenAPI({ description: 'Lists all information about the organisation whose id got provided.' })
	async getOne(@Param('id') id: number) {
		let runnerOrg = await this.runnerOrganisationRepository.findOne({ id: id }, { relations: ['address', 'contact', 'teams'] });
		if (!runnerOrg) { throw new RunnerOrganisationNotFoundError(); }
		return new ResponseRunnerOrganisation(runnerOrg);
	}

	@Post()
	@Authorized("ORGANISATION:CREATE")
	@ResponseSchema(ResponseRunnerOrganisation)
	@OpenAPI({ description: 'Create a new organsisation.' })
	async post(@Body({ validate: true }) createRunnerOrganisation: CreateRunnerOrganisation) {
		let runnerOrganisation;
		try {
			runnerOrganisation = await createRunnerOrganisation.toRunnerOrganisation();
		} catch (error) {
			throw error;
		}

		runnerOrganisation = await this.runnerOrganisationRepository.save(runnerOrganisation);

		return new ResponseRunnerOrganisation(await this.runnerOrganisationRepository.findOne(runnerOrganisation, { relations: ['address', 'contact', 'teams'] }));
	}

	@Put('/:id')
	@Authorized("ORGANISATION:UPDATE")
	@ResponseSchema(ResponseRunnerOrganisation)
	@ResponseSchema(RunnerOrganisationNotFoundError, { statusCode: 404 })
	@ResponseSchema(RunnerOrganisationIdsNotMatchingError, { statusCode: 406 })
	@OpenAPI({ description: "Update the organisation whose id you provided. <br> Please remember that ids can't be changed." })
	async put(@Param('id') id: number, @Body({ validate: true }) updateOrganisation: UpdateRunnerOrganisation) {
		let oldRunnerOrganisation = await this.runnerOrganisationRepository.findOne({ id: id });

		if (!oldRunnerOrganisation) {
			throw new RunnerOrganisationNotFoundError();
		}

		if (oldRunnerOrganisation.id != updateOrganisation.id) {
			throw new RunnerOrganisationIdsNotMatchingError();
		}

		await this.runnerOrganisationRepository.save(await updateOrganisation.updateRunnerOrganisation(oldRunnerOrganisation));

		return new ResponseRunnerOrganisation(await this.runnerOrganisationRepository.findOne(id, { relations: ['address', 'contact', 'teams'] }));
	}

	@Delete('/:id')
	@Authorized("ORGANISATION:DELETE")
	@ResponseSchema(ResponseRunnerOrganisation)
	@ResponseSchema(ResponseEmpty, { statusCode: 204 })
	@ResponseSchema(RunnerOrganisationHasTeamsError, { statusCode: 406 })
	@ResponseSchema(RunnerOrganisationHasRunnersError, { statusCode: 406 })
	@OnUndefined(204)
	@OpenAPI({ description: 'Delete the organsisation whose id you provided. <br> If the organisation still has runners and/or teams associated this will fail. <br> To delete the organisation with all associated runners and teams set the force QueryParam to true (cascading deletion might take a while). <br> If no organisation with this id exists it will just return 204(no content).' })
	async remove(@Param("id") id: number, @QueryParam("force") force: boolean) {
		let organisation = await this.runnerOrganisationRepository.findOne({ id: id });
		if (!organisation) { return null; }
		let runnerOrganisation = await this.runnerOrganisationRepository.findOne(organisation, { relations: ['address', 'contact', 'runners', 'teams'] });

		if (!force) {
			if (runnerOrganisation.teams.length != 0) {
				throw new RunnerOrganisationHasTeamsError();
			}
		}
		const teamController = new RunnerTeamController()
		for (let team of runnerOrganisation.teams) {
			await teamController.remove(team.id, true);
		}

		if (!force) {
			if (runnerOrganisation.runners.length != 0) {
				throw new RunnerOrganisationHasRunnersError();
			}
		}
		const runnerController = new RunnerController()
		for (let runner of runnerOrganisation.runners) {
			await runnerController.remove(runner.id, true);
		}

		const responseOrganisation = new ResponseRunnerOrganisation(runnerOrganisation);
		await this.runnerOrganisationRepository.delete(organisation);
		return responseOrganisation;
	}
}
