import { IsInt, IsPositive } from 'class-validator';
import { getConnectionManager } from 'typeorm';
import { RunnerOrganizationNotFoundError } from '../../../errors/RunnerOrganizationErrors';
import { RunnerTeamNeedsParentError } from '../../../errors/RunnerTeamErrors';
import { RunnerOrganization } from '../../entities/RunnerOrganization';
import { RunnerTeam } from '../../entities/RunnerTeam';
import { CreateRunnerGroup } from '../create/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's id.
     */
    @IsInt()
    @IsPositive()
    parentGroup: number;

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

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

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

        return team;
    }
}