import { IsBoolean, IsInt, IsObject, IsOptional } from 'class-validator';
import * as uuid from 'uuid';
import { Address } from '../../entities/Address';
import { RunnerOrganization } from '../../entities/RunnerOrganization';
import { CreateRunnerGroup } from '../create/CreateRunnerGroup';

/**
 * This class is used to update a RunnerOrganization entity (via put request).
 */
export class UpdateRunnerOrganization 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 organization's address.
     */
    @IsOptional()
    @IsObject()
    address?: Address;

    /**
     * Is registration enabled for the updated organization?
     */
    @IsOptional()
    @IsBoolean()
    registrationEnabled?: boolean = false;

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

        organization.name = this.name;
        organization.contact = await this.getContact();
        if (!this.address) { organization.address.reset(); }
        else { organization.address = this.address; }
        Address.validate(organization.address);

        if (this.registrationEnabled && !organization.key) {
            organization.key = uuid.v4().toUpperCase();
        }
        else {
            organization.key = null;
        }

        return organization;
    }
}