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 { DonorIdsNotMatchingError, DonorNotFoundError } from '../errors/DonorErrors';
import { CreateDonor } from '../models/actions/CreateDonor';
import { UpdateDonor } from '../models/actions/UpdateDonor';
import { Donor } from '../models/entities/Donor';
import { ResponseDonor } from '../models/responses/ResponseDonor';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';

@JsonController('/donors')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class DonorController {
	private donorRepository: Repository<Donor>;

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

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

	@Get('/:id')
	@Authorized("DONOR:GET")
	@ResponseSchema(ResponseDonor)
	@ResponseSchema(DonorNotFoundError, { statusCode: 404 })
	@OnUndefined(DonorNotFoundError)
	@OpenAPI({ description: 'Lists all information about the runner whose id got provided.' })
	async getOne(@Param('id') id: number) {
		let donor = await this.donorRepository.findOne({ id: id })
		if (!donor) { throw new DonorNotFoundError(); }
		return new ResponseDonor(donor);
	}

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

		donor = await this.donorRepository.save(donor)
		return new ResponseDonor(await this.donorRepository.findOne(donor));
	}

	@Put('/:id')
	@Authorized("DONOR:UPDATE")
	@ResponseSchema(ResponseDonor)
	@ResponseSchema(DonorNotFoundError, { statusCode: 404 })
	@ResponseSchema(DonorIdsNotMatchingError, { 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 }) donor: UpdateDonor) {
		let oldDonor = await this.donorRepository.findOne({ id: id });

		if (!oldDonor) {
			throw new DonorNotFoundError();
		}

		if (oldDonor.id != donor.id) {
			throw new DonorIdsNotMatchingError();
		}

		await this.donorRepository.save(await donor.updateDonor(oldDonor));
		return new ResponseDonor(await this.donorRepository.findOne({ id: id }));
	}

	@Delete('/:id')
	@Authorized("DONOR:DELETE")
	@ResponseSchema(ResponseDonor)
	@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 donor = await this.donorRepository.findOne({ id: id });
		if (!donor) { return null; }
		const responseDonor = await this.donorRepository.findOne(donor);

		if (!donor) {
			throw new DonorNotFoundError();
		}

		//TODO: DELETE DONATIONS AND WARN FOR FORCE (https://git.odit.services/lfk/backend/issues/66)

		await this.donorRepository.delete(donor);
		return new ResponseDonor(responseDonor);
	}
}
