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 { RunnerTeamHasRunnersError, RunnerTeamIdsNotMatchingError, RunnerTeamNotFoundError } from '../errors/RunnerTeamErrors';
import { CreateRunnerTeam } from '../models/actions/create/CreateRunnerTeam';
import { UpdateRunnerTeam } from '../models/actions/update/UpdateRunnerTeam';
import { RunnerTeam } from '../models/entities/RunnerTeam';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseRunner } from '../models/responses/ResponseRunner';
import { ResponseRunnerTeam } from '../models/responses/ResponseRunnerTeam';
import { RunnerController } from './RunnerController';


@JsonController('/teams')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class RunnerTeamController {
	private runnerTeamRepository: Repository<RunnerTeam>;

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

	@Get()
	@Authorized("TEAM:GET")
	@ResponseSchema(ResponseRunnerTeam, { isArray: true })
	@OpenAPI({ description: 'Lists all teams. <br> This includes their parent organization and contact (if existing/associated).' })
	async getAll(@QueryParam("page", { required: false }) page: number, @QueryParam("page_size", { required: false }) page_size: number = 100) {
		let responseTeams: ResponseRunnerTeam[] = new Array<ResponseRunnerTeam>();
		let teams: Array<RunnerTeam>;

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

		teams.forEach(team => {
			responseTeams.push(new ResponseRunnerTeam(team));
		});
		return responseTeams;
	}

	@Get('/:id')
	@Authorized("TEAM:GET")
	@ResponseSchema(ResponseRunnerTeam)
	@ResponseSchema(RunnerTeamNotFoundError, { statusCode: 404 })
	@OnUndefined(RunnerTeamNotFoundError)
	@OpenAPI({ description: 'Lists all information about the team whose id got provided.' })
	async getOne(@Param('id') id: number) {
		let runnerTeam = await this.runnerTeamRepository.findOne({ id: id }, { relations: ['parentGroup', 'contact', 'runners', 'runners.scans', 'runners.scans.track'] });
		if (!runnerTeam) { throw new RunnerTeamNotFoundError(); }
		return new ResponseRunnerTeam(runnerTeam);
	}

	@Get('/:id/runners')
	@Authorized(["RUNNER:GET", "SCAN:GET"])
	@ResponseSchema(ResponseRunner, { isArray: true })
	@ResponseSchema(RunnerTeamNotFoundError, { statusCode: 404 })
	@OpenAPI({ description: 'Lists all runners from this team. <br> This includes the runner\'s group and distance ran.' })
	async getRunners(@Param('id') id: number, @QueryParam("selfservice_links", { required: false }) selfservice_links: boolean = false) {
		let responseRunners: ResponseRunner[] = new Array<ResponseRunner>();
		const runners = (await this.runnerTeamRepository.findOne({ id: id }, { relations: ['runners', 'runners.group', 'runners.group.parentGroup', 'runners.scans', 'runners.scans.track'] })).runners;
		runners.forEach(runner => {
			responseRunners.push(new ResponseRunner(runner, selfservice_links));
		});
		return responseRunners;
	}

	@Post()
	@Authorized("TEAM:CREATE")
	@ResponseSchema(ResponseRunnerTeam)
	@OpenAPI({ description: 'Create a new organsisation. <br> Please remember to provide it\'s parent group\'s id.' })
	async post(@Body({ validate: true }) createRunnerTeam: CreateRunnerTeam) {
		let runnerTeam;
		try {
			runnerTeam = await createRunnerTeam.toEntity();
		} catch (error) {
			throw error;
		}

		runnerTeam = await this.runnerTeamRepository.save(runnerTeam);
		runnerTeam = await this.runnerTeamRepository.findOne(runnerTeam, { relations: ['parentGroup', 'contact'] });

		return new ResponseRunnerTeam(runnerTeam);
	}

	@Put('/:id')
	@Authorized("TEAM:UPDATE")
	@ResponseSchema(ResponseRunnerTeam)
	@ResponseSchema(RunnerTeamNotFoundError, { statusCode: 404 })
	@ResponseSchema(RunnerTeamIdsNotMatchingError, { statusCode: 406 })
	@OpenAPI({ description: "Update the team whose id you provided. <br> Please remember that ids can't be changed." })
	async put(@Param('id') id: number, @Body({ validate: true }) runnerTeam: UpdateRunnerTeam) {
		let oldRunnerTeam = await this.runnerTeamRepository.findOne({ id: id }, { relations: ['parentGroup', 'contact'] });

		if (!oldRunnerTeam) {
			throw new RunnerTeamNotFoundError();
		}

		if (oldRunnerTeam.id != runnerTeam.id) {
			throw new RunnerTeamIdsNotMatchingError();
		}

		await this.runnerTeamRepository.save(await runnerTeam.update(oldRunnerTeam));

		return new ResponseRunnerTeam(await this.runnerTeamRepository.findOne({ id: runnerTeam.id }, { relations: ['parentGroup', 'contact'] }));
	}

	@Delete('/:id')
	@Authorized("TEAM:DELETE")
	@ResponseSchema(ResponseRunnerTeam)
	@ResponseSchema(ResponseEmpty, { statusCode: 204 })
	@ResponseSchema(RunnerTeamHasRunnersError, { statusCode: 406 })
	@OnUndefined(204)
	@OpenAPI({ description: 'Delete the team whose id you provided. <br> If the team still has runners associated this will fail. <br> To delete the team with all associated runners set the force QueryParam to true (cascading deletion might take a while). <br> This won\'t delete the associated contact.<br> If no team with this id exists it will just return 204(no content).' })
	async remove(@Param("id") id: number, @QueryParam("force") force: boolean) {
		let team = await this.runnerTeamRepository.findOne({ id: id });
		if (!team) { return null; }
		let runnerTeam = await this.runnerTeamRepository.findOne(team, { relations: ['runners'] });

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

		const responseTeam = new ResponseRunnerTeam(runnerTeam);
		await this.runnerTeamRepository.delete(team);
		return responseTeam;
	}
}
