import { IsInt, IsPositive } from 'class-validator';
import { getConnectionManager } from 'typeorm';
import { RunnerGroupNotFoundError } from '../../../errors/RunnerGroupErrors';
import { RunnerTeamNeedsParentError } from '../../../errors/RunnerTeamErrors';
import { Address } from '../../entities/Address';
import { Runner } from '../../entities/Runner';
import { RunnerGroup } from '../../entities/RunnerGroup';
import { CreateParticipant } from '../create/CreateParticipant';

/**
 * This class is used to update a Runner entity (via put request).
 */
export class UpdateRunner extends CreateParticipant {

    /**
     * The updated runner'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 runner's group's id.
     */
    @IsInt()
    @IsPositive()
    group: number;

    /**
     * Updates a provided Runner entity based on this.
     */
    public async update(runner: Runner): Promise<Runner> {
        runner.firstname = this.firstname;
        runner.middlename = this.middlename;
        runner.lastname = this.lastname;
        runner.phone = this.phone;
        runner.email = this.email;
        runner.group = await this.getGroup();
        if (!this.address) { runner.address.reset(); }
        else { runner.address = this.address; }
        Address.validate(runner.address);

        return runner;
    }

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