import { IsInt, IsNotEmpty } 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 './CreateRunnerGroup';

/**
 * This classed is used to create a new RunnerTeam entity from a json body (post request).
 */
export class CreateRunnerTeam extends CreateRunnerGroup {

    /**
     * The new team's parent org's id.
     */
    @IsInt()
    @IsNotEmpty()
    parentGroup: number;

    /**
     * Gets the new team's parent org 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;
    }

    /**
     * Creates a new RunnerTeam entity from this.
     */
    public async toEntity(): Promise<RunnerTeam> {
        let newRunnerTeam: RunnerTeam = new RunnerTeam();

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

        return newRunnerTeam;
    }
}