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 { RunnerGroupNeededError, RunnerIdsNotMatchingError, RunnerNotFoundError } from '../errors/RunnerErrors';
import { RunnerGroupNotFoundError } from '../errors/RunnerGroupErrors';
import { CreateRunner } from '../models/actions/CreateRunner';
import { UpdateRunner } from '../models/actions/UpdateRunner';
import { Runner } from '../models/entities/Runner';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseRunner } from '../models/responses/ResponseRunner';

@JsonController('/runners')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class RunnerController {
	private runnerRepository: Repository<Runner>;

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

	@Get()
	@Authorized("RUNNER:GET")
	@ResponseSchema(ResponseRunner, { isArray: true })
	@OpenAPI({ description: 'Lists all runners from all teams/orgs. <br> This includes the runner\'s group and distance ran.' })
	async getAll() {
		let responseRunners: ResponseRunner[] = new Array<ResponseRunner>();
		const runners = await this.runnerRepository.find({ relations: ['scans', 'group'] });
		runners.forEach(runner => {
			responseRunners.push(new ResponseRunner(runner));
		});
		return responseRunners;
	}

	@Get('/:id')
	@Authorized("RUNNER:GET")
	@ResponseSchema(ResponseRunner)
	@ResponseSchema(RunnerNotFoundError, { statusCode: 404 })
	@OnUndefined(RunnerNotFoundError)
	@OpenAPI({ description: 'Lists all information about the runner whose id got provided.' })
	async getOne(@Param('id') id: number) {
		let runner = await this.runnerRepository.findOne({ id: id }, { relations: ['scans', 'group'] })
		if (!runner) { throw new RunnerNotFoundError(); }
		return new ResponseRunner(runner);
	}

	@Post()
	@Authorized("RUNNER:CREATE")
	@ResponseSchema(ResponseRunner)
	@ResponseSchema(RunnerGroupNeededError)
	@ResponseSchema(RunnerGroupNotFoundError)
	@OpenAPI({ description: 'Create a new runner. <br> Please remeber to provide the runner\'s group\'s id.' })
	async post(@Body({ validate: true }) createRunner: CreateRunner) {
		let runner;
		try {
			runner = await createRunner.toRunner();
		} catch (error) {
			throw error;
		}

		runner = await this.runnerRepository.save(runner)
		return new ResponseRunner(await this.runnerRepository.findOne(runner, { relations: ['scans', 'group'] }));
	}

	@Put('/:id')
	@Authorized("RUNNER:UPDATE")
	@ResponseSchema(ResponseRunner)
	@ResponseSchema(RunnerNotFoundError, { statusCode: 404 })
	@ResponseSchema(RunnerIdsNotMatchingError, { statusCode: 406 })
	@OpenAPI({ description: "Update the runner whose id you provided. <br> Please remember that ids can't be changed." })
	async put(@Param('id') id: number, @Body({ validate: true }) runner: UpdateRunner) {
		let oldRunner = await this.runnerRepository.findOne({ id: id }, { relations: ['group'] });

		if (!oldRunner) {
			throw new RunnerNotFoundError();
		}

		if (oldRunner.id != runner.id) {
			throw new RunnerIdsNotMatchingError();
		}

		await this.runnerRepository.save(await runner.updateRunner(oldRunner));
		return new ResponseRunner(await this.runnerRepository.findOne({ id: id }, { relations: ['scans', 'group'] }));
	}

	@Delete('/:id')
	@Authorized("RUNNER:DELETE")
	@ResponseSchema(ResponseRunner)
	@ResponseSchema(ResponseEmpty, { statusCode: 204 })
	@OnUndefined(204)
	@OpenAPI({ description: 'Delete the runner whose id you provided. <br> If no runner with this id exists it will just return 204(no content).' })
	async remove(@Param("id") id: number, @QueryParam("force") force: boolean) {
		let runner = await this.runnerRepository.findOne({ id: id });
		if (!runner) { return null; }
		const responseRunner = await this.runnerRepository.findOne(runner, { relations: ['scans', 'group'] });

		if (!runner) {
			throw new RunnerNotFoundError();
		}

		await this.runnerRepository.delete(runner);
		return new ResponseRunner(responseRunner);
	}
}
