import { Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, QueryParam } from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { Repository, getConnectionManager } from 'typeorm';
import { StatsClientNotFoundError } from '../errors/StatsClientErrors';
import { TrackNotFoundError } from "../errors/TrackErrors";
import { CreateStatsClient } from '../models/actions/create/CreateStatsClient';
import { StatsClient } from '../models/entities/StatsClient';
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
import { ResponseStatsClient } from '../models/responses/ResponseStatsClient';

@JsonController('/statsclients')
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
export class StatsClientController {
	private clientRepository: Repository<StatsClient>;

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

	@Get()
	@Authorized("STATSCLIENT:GET")
	@ResponseSchema(ResponseStatsClient, { isArray: true })
	@OpenAPI({ description: 'Lists all stats clients. Please remember that the key can only be viewed on creation.' })
	async getAll(@QueryParam("page", { required: false }) page: number, @QueryParam("page_size", { required: false }) page_size: number = 100) {
		let responseClients: ResponseStatsClient[] = new Array<ResponseStatsClient>();
		let clients: Array<StatsClient>;

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

		clients.forEach(clients => {
			responseClients.push(new ResponseStatsClient(clients));
		});
		return responseClients;
	}

	@Get('/:id')
	@Authorized("STATSCLIENT:GET")
	@ResponseSchema(ResponseStatsClient)
	@ResponseSchema(StatsClientNotFoundError, { statusCode: 404 })
	@OnUndefined(StatsClientNotFoundError)
	@OpenAPI({ description: "Lists all information about the stats client whose id got provided. Please remember that the key can only be viewed on creation." })
	async getOne(@Param('id') id: number) {
		let client = await this.clientRepository.findOne({ id: id });
		if (!client) { throw new TrackNotFoundError(); }
		return new ResponseStatsClient(client);
	}

	@Post()
	@Authorized("STATSCLIENT:CREATE")
	@ResponseSchema(ResponseStatsClient)
	@OpenAPI({ description: "Create a new stats client. <br> Please remember that the client\'s key will be generated automaticly and that it can only be viewed on creation." })
	async post(
		@Body({ validate: true })
		client: CreateStatsClient
	) {
		let newClient = await this.clientRepository.save(await client.toEntity());
		let responseClient = new ResponseStatsClient(newClient);
		responseClient.key = newClient.cleartextkey;
		return responseClient;
	}

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

		await this.clientRepository.delete(client);
		return new ResponseStatsClient(client);
	}
}