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

/**
 * This classed is used to create a new Donor entity from a json body (post request).
 */
export class CreateDonor extends CreateParticipant {

    /**
     * Does this donor need a receipt?
     */
    @IsBoolean()
    @IsOptional()
    receiptNeeded?: boolean = false;

    /**
     * Creates a new Donor entity from this.
     */
    public async toEntity(): Promise<Donor> {
        let newDonor: Donor = new Donor();

        newDonor.firstname = this.firstname;
        newDonor.middlename = this.middlename;
        newDonor.lastname = this.lastname;
        newDonor.phone = this.phone;
        newDonor.email = this.email;
        newDonor.receiptNeeded = this.receiptNeeded;
        newDonor.address = this.address;
        Address.validate(newDonor.address);
        if (this.receiptNeeded == true && Address.isValidAddress(newDonor.address) == false) {
            throw new DonorReceiptAddressNeededError()
        }

        return newDonor;
    }
}