import { IsInt, IsOptional } from "class-validator";
import { ChildEntity, ManyToOne, OneToMany } from "typeorm";
import { Address } from './Address';
import { IAddressUser } from './IAddressUser';
import { Runner } from './Runner';
import { RunnerGroup } from "./RunnerGroup";
import { RunnerTeam } from "./RunnerTeam";

/**
 * Defines the RunnerOrganisation entity.
 * This usually is a school, club or company.
*/
@ChildEntity()
export class RunnerOrganisation extends RunnerGroup implements IAddressUser {

  /**
   * The organisations's address.
   */
  @IsOptional()
  @ManyToOne(() => Address, address => address.addressUsers, { nullable: true })
  address?: Address;

  /**
   * The organisation's teams.
   * Used to link teams to a organisation.
   */
  @OneToMany(() => RunnerTeam, team => team.parentGroup, { nullable: true })
  teams: RunnerTeam[];

  /**
   * Returns all runners associated with this organisation (directly or indirectly via teams).
   */
  public get allRunners(): Runner[] {
    let returnRunners: Runner[] = new Array<Runner>();
    returnRunners.push(...this.runners);
    for (let team of this.teams) {
      returnRunners.push(...team.runners)
    }
    return returnRunners;
  }

  /**
   * Returns the total distance ran by this group's runners based on all their valid scans.
  */
  @IsInt()
  public get distance(): number {
    return this.allRunners.reduce((sum, current) => sum + current.distance, 0);
  }

  /**
   * Returns the total donations a runner has collected based on his linked donations and distance ran.
  */
  @IsInt()
  public get distanceDonationAmount(): number {
    return this.allRunners.reduce((sum, current) => sum + current.distanceDonationAmount, 0);
  }
}