import { Authorized, Body, Get, JsonController, OnUndefined, Param, Post } from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { getConnectionManager, Repository } from 'typeorm';
import { ScanNotFoundError } from '../errors/ScanErrors';
import { CreateScan } from '../models/actions/CreateScan';
import { Scan } from '../models/entities/Scan';
import { ResponseScan } from '../models/responses/ResponseScan';
import { ResponseTrackScan } from '../models/responses/ResponseTrackScan';

@JsonController('/scans')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class ScanController {
	private scanRepository: Repository<Scan>;

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

	@Get()
	@Authorized("SCAN:GET")
	@ResponseSchema(ResponseScan, { isArray: true })
	@ResponseSchema(ResponseTrackScan, { isArray: true })
	@OpenAPI({ description: 'Lists all scans (normal or track) from all runners. <br> This includes the runner\'s group and distance ran.' })
	async getAll() {
		let responseScans: ResponseScan[] = new Array<ResponseScan>();
		const scans = await this.scanRepository.find({ relations: ['runner'] });
		scans.forEach(scan => {
			responseScans.push(scan.toResponse());
		});
		return responseScans;
	}

	@Get('/:id')
	@Authorized("SCAN:GET")
	@ResponseSchema(ResponseScan)
	@ResponseSchema(ResponseTrackScan)
	@ResponseSchema(ScanNotFoundError, { statusCode: 404 })
	@OnUndefined(ScanNotFoundError)
	@OpenAPI({ description: 'Lists all information about the runner whose id got provided.' })
	async getOne(@Param('id') id: number) {
		let scan = await this.scanRepository.findOne({ id: id }, { relations: ['runner'] })
		if (!scan) { throw new ScanNotFoundError(); }
		return scan.toResponse();
	}

	@Post()
	@Authorized("SCAN:CREATE")
	@ResponseSchema(ResponseScan)
	@OpenAPI({ description: 'Create a new runner. <br> Please remeber to provide the runner\'s group\'s id.' })
	async post(@Body({ validate: true }) createScan: CreateScan) {
		let scan = await createScan.toScan();
		scan = await this.scanRepository.save(scan);
		console.log(scan);
		return (await this.scanRepository.findOne({ id: scan.id }, { relations: ['runner'] })).toResponse();
	}

	// @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);
	// }
}
