package edu.columbia.cs.cs1007.company;

import java.util.ArrayList;
import java.util.Random;

/**
 * A class that represents a department manager in a company.
 
 @author Julia Stoyanovich, COMS 1007, Summer 2009.
 *
 */

public class Manager extends Employee {
  
  // employees who report to the manager
  protected ArrayList<Employee> _reports;
  // manager's title
  protected String _title;
  
  /**
   * Constructor.
   @param person 
   @param company
   @param manager
   @param salary
   */
  public Manager(Person person, Company company, Manager manager, double salary) {
    
    super(person, company, manager, salary);
    _reports = new ArrayList<Employee>();
    _title = "Department Manager";
  }
  
  /**
   * Hire a person to work for the this manager.
   @param person
   @param salary
   @return an instance of Employee
   */
  public Employee hire(Person person, double salary) {
    
    Employee employee = new Employee(person, this._company, this, salary);
    
    _reports.add(employee);
    return employee;
  }
  
  /**
   * Fire an employee.
   @param employee
   @return true on success, false on failure
   */
  public boolean fire(Employee employee) {
    
    boolean greatSuccess = false;

    for (int i=0; i<_reports.size(); i++) {
      if (employee.equals(_reports.get(i))) {
        _reports.remove(i);
        greatSuccess = true;
        break;
      }
    }
    return greatSuccess;
  }
  
  /**
   * Do work: delegate to an employee, or do the work yourself if
   * no-one reports to you.
   @param  toDo description of the work
   @return progress report
   */
  public String doWork(String toDo) {
    
    String workDone;
    if (_reports.size() 0) {
      workDone = delegateWork(toDo);
    else {
      workDone = super.doWork(toDo);
    }
    return workDone;
  }
  
  /**
   * Delegate work to another employee.  Caller of this method checks whether
   * any other employees report to this manager.
   @param toDo description of the work
   @return progress report
   */
  protected String delegateWork(String toDo) {
    
    // pick an employee from among the reports, at random
    Random rand = new Random();
    int i = rand.nextInt(_reports.size());
      
    // delegate work to that employee
    return _reports.get(i).doWork(toDo);
  }
  
  /**
   * Give raise to an employee.
   @param employee
   @param percentIncrement
   */
  public void giveRaise(Employee employee, double percentIncrement) {
    employee.getRaise(percentIncrement);
  }

  /**
   * Generate a string representation of the manager.
   @return string representation
   */
  public String toString() {
    return _title + super.toString();
  }
  
}