package ug.ufe.employe;

import java.util.*;

/**
 * Représente une entreprise
 */
public class Entreprise {
  private String nom;
  private ArrayList<Employe> employes;
  private static ArrayList<Entreprise> entreprises = new ArrayList<>();

  public Entreprise(String nom) {
    this.nom = nom;
    employes = new ArrayList<>();
    entreprises.add(this);
  }
  
  public String getNom() {
    return nom;
  }

  public boolean aPourEmploye(Employe emp) {
    return employes.contains(emp);
  }

  public void engager(Employe emp) throws EmployeException {
    if (! employes.add(emp)) {
      throw new EmployeException(emp.getNom() + " déjà  dans cette entreprise");
    }
    // Enlever l'employé d'une éventuelle ancienne entreprise
    for (Entreprise entreprise : entreprises) {
      if (entreprise != this && entreprise.aPourEmploye(emp)) {
        entreprise.seSeparerDe(emp);
      }
    }
  }

  public void seSeparerDe(Employe emp) throws EmployeException {
    if (! employes.remove(emp)) {
      throw new EmployeException(emp.getNom() + " pas dans " + this.nom);
    }
  }

  public String toString() {
    StringBuilder sb = 
      new StringBuilder("[" + this.getClass() + ":" + nom + ";");
    for (Employe employe : employes) {
      sb.append(employe.getNom() + "|");
    }
    sb.append("]");
    return sb.toString();
  }
}