import { IsBoolean, IsInt, IsOptional } from 'class-validator';
import { DonorReceiptAddressNeededError } from '../../../errors/DonorErrors';
import { Address } from '../../entities/Address';
import { Donor } from '../../entities/Donor';
import { CreateParticipant } from '../create/CreateParticipant';

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

    /**
     * The updated donor'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;

    /**
     * Does the updated donor need a receipt?
     */
    @IsBoolean()
    @IsOptional()
    receiptNeeded?: boolean;


    /**
     * Updates a provided Donor entity based on this.
     */
    public async update(donor: Donor): Promise<Donor> {
        donor.firstname = this.firstname;
        donor.middlename = this.middlename;
        donor.lastname = this.lastname;
        donor.phone = this.phone;
        donor.email = this.email;
        donor.receiptNeeded = this.receiptNeeded;
        if (!this.address) { donor.address.reset(); }
        else { donor.address = this.address; }
        Address.validate(donor.address);
        if (this.receiptNeeded == true && Address.isValidAddress(donor.address) == false) {
            throw new DonorReceiptAddressNeededError()
        }

        return donor;
    }
}