import java.io.*;
import java.util.*;

/** 
 *  Demo program showing how to write data to a text file 
 *
 *  @author Nick Howe
 *  @version 9 April 2013
 */
public class WriteEmployeesAsText {
    /** We need this to set up some data to write out.
        In a real program, this would be the result of 
        some more interesting process. */
    public static LinkedList<Employee> setupData() {
        LinkedList<Employee> employees = new LinkedList<Employee>();
        employees.add(new Employee("Dilbert",35000));
        employees.add(new Employee("Alice",50000));
        employees.add(new Employee("Wally",35000));
        employees.add(new Employee("Asok",8000));
        employees.add(new Employee("Pointy-Haired Boss",80000));
        employees.add(new Employee("Dogbert",200000));
        return employees;
    }

    /** Write employee information to external file */
    public static void writeTextFile(String fileName, 
                                     LinkedList<Employee> employees) {
        // encase all output in try/catch in case of error
        try {
            // Open a file and create a PrintWriter to it
            PrintWriter out = new PrintWriter(new FileWriter(fileName));
            
            // loop through employees and print a line for each
            for (Employee e: employees) {
                out.print(e.getName());
                out.format(" $%1.2f\n",e.getSalary());
            }
            
            // file contents aren't written until file is closed
            out.close();
        } catch (IOException e) {
            System.err.println("Problem writing to file.");
        }
    }

    /** The main method calls one method to set up, and another to output */
    public static void main(String[] args) {
        LinkedList<Employee> employees = setupData();

        try {
            writeTextFile(args[0],employees);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Usage:  java WriteEmployeesAsText employees.txt");
        }
    }
}
