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 { TrackHasScanStationsError, TrackIdsNotMatchingError, TrackLapTimeCantBeNegativeError, TrackNotFoundError } from "../errors/TrackErrors";
import { CreateTrack } from '../models/actions/create/CreateTrack';
import { UpdateTrack } from '../models/actions/update/UpdateTrack';
import { Track } from '../models/entities/Track';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseTrack } from '../models/responses/ResponseTrack';
import { ScanStationController } from './ScanStationController';

@JsonController('/tracks')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class TrackController {
	private trackRepository: Repository<Track>;

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

	@Get()
	@Authorized("TRACK:GET")
	@ResponseSchema(ResponseTrack, { isArray: true })
	@OpenAPI({ description: 'Lists all tracks.' })
	async getAll(@QueryParam("page", { required: false }) page: number, @QueryParam("page_size", { required: false }) page_size: number = 100) {
		let responseTracks: ResponseTrack[] = new Array<ResponseTrack>();
		let tracks: Array<Track>;

		if (page != undefined) {
			tracks = await this.trackRepository.find({ skip: page * page_size, take: page_size });
		}
		else {
			tracks = await this.trackRepository.find();
		}

		tracks.forEach(track => {
			responseTracks.push(new ResponseTrack(track));
		});
		return responseTracks;
	}

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

	@Post()
	@Authorized("TRACK:CREATE")
	@ResponseSchema(ResponseTrack)
	@ResponseSchema(TrackLapTimeCantBeNegativeError, { statusCode: 406 })
	@OpenAPI({ description: "Create a new track. <br> Please remember that the track\'s distance must be greater than 0." })
	async post(
		@Body({ validate: true })
		track: CreateTrack
	) {
		return new ResponseTrack(await this.trackRepository.save(await track.toEntity()));
	}

	@Put('/:id')
	@Authorized("TRACK:UPDATE")
	@ResponseSchema(ResponseTrack)
	@ResponseSchema(TrackNotFoundError, { statusCode: 404 })
	@ResponseSchema(TrackIdsNotMatchingError, { statusCode: 406 })
	@ResponseSchema(TrackLapTimeCantBeNegativeError, { statusCode: 406 })
	@OpenAPI({ description: "Update the track whose id you provided. <br> Please remember that ids can't be changed." })
	async put(@Param('id') id: number, @Body({ validate: true }) updateTrack: UpdateTrack) {
		let oldTrack = await this.trackRepository.findOne({ id: id });

		if (!oldTrack) {
			throw new TrackNotFoundError();
		}

		if (oldTrack.id != updateTrack.id) {
			throw new TrackIdsNotMatchingError();
		}
		await this.trackRepository.save(await updateTrack.update(oldTrack));

		return new ResponseTrack(await this.trackRepository.findOne({ id: id }));
	}

	@Delete('/:id')
	@Authorized("TRACK:DELETE")
	@ResponseSchema(ResponseTrack)
	@ResponseSchema(ResponseEmpty, { statusCode: 204 })
	@OnUndefined(204)
	@OpenAPI({ description: "Delete the track whose id you provided. <br> If no track with this id exists it will just return 204(no content)." })
	async remove(@Param("id") id: number, @QueryParam("force") force: boolean) {
		let track = await this.trackRepository.findOne({ id: id });
		if (!track) { return null; }

		const trackStations = (await this.trackRepository.findOne({ id: id }, { relations: ["stations"] })).stations;
		if (trackStations.length != 0 && !force) {
			throw new TrackHasScanStationsError();
		}
		const stationController = new ScanStationController;
		for (let station of trackStations) {
			await stationController.remove(station.id, force);
		}

		await this.trackRepository.delete(track);
		return new ResponseTrack(track);
	}
}