import { IsInt, IsNotEmpty, IsObject } from 'class-validator';
import { getConnectionManager } from 'typeorm';
import { RunnerOrganisationNotFoundError, RunnerOrganisationWrongTypeError } from '../../errors/RunnerOrganisationErrors';
import { RunnerTeamNeedsParentError } from '../../errors/RunnerTeamErrors';
import { RunnerOrganisation } from '../entities/RunnerOrganisation';
import { RunnerTeam } from '../entities/RunnerTeam';
import { CreateRunnerGroup } from './CreateRunnerGroup';

/**
 * This class is used to update a RunnerTeam entity (via put request).
 */
export class UpdateRunnerTeam extends CreateRunnerGroup {

    /**
     * The updated team's id.
     * This shouldn't have changed but it is here in case anyone ever wants to enable id changes (whyever they would want to).
     */
    @IsInt()
    id: number;

    /**
     * The updated team's parentGroup.
     * Just has to contain the organisation's id - everything else won't be checked or changed.
     */
    @IsObject()
    @IsNotEmpty()
    parentGroup: RunnerOrganisation;

    /**
     * Loads the updated teams's parentGroup based on it's id.
     */
    public async getParent(): Promise<RunnerOrganisation> {
        if (this.parentGroup === undefined || this.parentGroup === null) {
            throw new RunnerTeamNeedsParentError();
        }
        if (!isNaN(this.parentGroup.id)) {
            let parentGroup = await getConnectionManager().get().getRepository(RunnerOrganisation).findOne({ id: this.parentGroup.id });
            if (!parentGroup) { throw new RunnerOrganisationNotFoundError();; }
            return parentGroup;
        }

        throw new RunnerOrganisationWrongTypeError;
    }

    /**
     * Updates a provided RunnerTeam entity based on this.
     */
    public async updateRunnerTeam(team: RunnerTeam): Promise<RunnerTeam> {

        team.name = this.name;
        team.parentGroup = await this.getParent();
        team.contact = await this.getContact()

        return team;
    }
}