import { IsInt, IsOptional } from 'class-validator';
import { getConnectionManager } from 'typeorm';
import { AddressNotFoundError, AddressWrongTypeError } from '../../errors/AddressErrors';
import { Address } from '../entities/Address';
import { RunnerOrganisation } from '../entities/RunnerOrganisation';
import { CreateRunnerGroup } from './CreateRunnerGroup';

/**
 * This classed is used to create a new RunnerOrganisation entity from a json body (post request).
 */
export class CreateRunnerOrganisation extends CreateRunnerGroup {
    /**
     * The new organisation's address.
     * Must be of type number (address id).
     */
    @IsInt()
    @IsOptional()
    address?: number;

    /**
     * Gets the org's address by it's id.
     */
    public async getAddress(): Promise<Address> {
        if (this.address === undefined || this.address === null) {
            return null;
        }
        if (!isNaN(this.address)) {
            let address = await getConnectionManager().get().getRepository(Address).findOne({ id: this.address });
            if (!address) { throw new AddressNotFoundError; }
            return address;
        }

        throw new AddressWrongTypeError;
    }

    /**
     * Creates a new RunnerOrganisation entity from this.
     */
    public async toRunnerOrganisation(): Promise<RunnerOrganisation> {
        let newRunnerOrganisation: RunnerOrganisation = new RunnerOrganisation();

        newRunnerOrganisation.name = this.name;
        newRunnerOrganisation.contact = await this.getContact();
        // newRunnerOrganisation.address = await this.getAddress();

        return newRunnerOrganisation;
    }
}