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

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

    /**
     * The updated orgs'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 organisation's address.
     * Just has to contain the address's id - everything else won't be checked or changed.
     * Optional.
     */
    @IsInt()
    @IsOptional()
    address?: Address;

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

    /**
     * Updates a provided RunnerOrganisation entity based on this.
     */
    public async updateRunnerOrganisation(organisation: RunnerOrganisation): Promise<RunnerOrganisation> {

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

        return organisation;
    }
}