/*
 * CS 178 Programming with Multimedia Objects
 * Created on Oct 19, 2004
 * Revised Oct 26.
 *
 * Illustrates simple input and output from data files. 
 * First data is written into a file. Then it is read from the file and displayed.
 * Exceptions are handled.
 * */

/**
 * @author adityamathur
 *
 *
 */

import java.applet.Applet;
import java.awt.Color;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileIOExample extends Applet implements ActionListener{
	
	Button record=new Button("Record Data");
	Button display =new Button("Display Data");
	Button done=new Button("Save to File");
	Button erase=new Button("Erase File");
	Button fileNameTyped=new Button ("Record File Name");
	TextField dataField=new TextField("Data", 50);
	
	// Define  file names for the input and output files.
	
	// String planetDataFile="planetFile";
	
	String planetDataFile;
	boolean fileNameSet=false;
	boolean saved=true; // Data already saved (actually there was no data inout and hence we assume it is saved!
	
	// Array of strings to hold string data.
	
	int maxPlanets=10; // Max number of planets that can be recorded.
	int maxNameLen=10;  // Max length of a planet name.
	int planetsRecorded=0; // Number of planets recorded so far in the planets array.
	String [] planets=new String [maxPlanets];
	TextArea planetDisplay=new TextArea(10, 30); // This is where we will display the planets read from a file.

	


	
	
	public void init(){
		
		// Add action listeners to the buttons.
		
	record.addActionListener(this);
	display.addActionListener(this);
	done.addActionListener(this);
	fileNameTyped.addActionListener(this);
	
	// Add all widgets to the screen.
	
	add(record); add(display); add(done); add(fileNameTyped);
	add(dataField);
	add(planetDisplay);
	setBackground(Color.orange);

	}

	
	
	public void actionPerformed(ActionEvent event){
		
		Object source=event.getSource(); // Get the name of the button pressed.
		
		
			try{
				if(source==record)recordPlanets();
				else if(source==done)writePlanetsToFile();
				else if(source==display)displayPlanets();
				else{
					fileNameSet=false;
					planetDataFile=getFileName();
				}
			}
			catch(Exception e){
				dataField.setText("Type File Name. Exception: "+e.getMessage());
				
				return;
	}
	
		}
	
public void fileReadAndDisplay(String filename) throws IOException{
	

		FileInputStream inFile=new FileInputStream(filename);
		DataInputStream in=new DataInputStream(inFile);
		
		int planetsToRead=in.readInt(); // Get the number of planets in the file.

		// Return if there is nothing to read.
		
		if (planetsToRead<=0){
			dataField.setText("Nothing to display.");
			return;
		}
	
		// Otherwise read planet names and display seqeuntially.
		
		
		for(int i=0; i<planetsToRead;i++){
			int planetNameLength=in.readInt();;
			String planetName=getNextName(planetNameLength, in);
			planetDisplay.append(planetName+"\n");
			
		}
		dataField.setText("Data displayed.");
		// in.close(); // Close the input data file.
			
		}
	

public void fileWrite(String filename) throws IOException{
	

		FileOutputStream outFile=new FileOutputStream(filename);
	DataOutputStream out=new DataOutputStream(outFile);
	
	
	// Write the entire planetName array into the planetFile.
	// First we write the number of planets into the file.
	// This is followed by the length and name of each planet. 
	// For example, if we have three planets Mars, Jupitor, and Saturn, then the foile will contain data in the following sequence:
	// 3 4 Mars 7 Jupitor 6 Saturn.
	// Note that there will be no spaces between the data items and that integers will be saved as two bytes.
	
	
	
	// First check if there are any planets to save in the file.
	
	if(planetsRecorded==0){
		dataField.setText("Nothing to record");
		return;
	}
	
	// If there is at least one planet to save then save it buddy!
	
	out.writeInt(planetsRecorded);
	for(int i=0;i<planetsRecorded; i++){
		out.writeInt(planets[i].length());;
		out.writeChars(planets[i]);
	}
	
	// Close the output stream.
	
	out.close();
	dataField.setText("Planet names written:" +planetsRecorded+" tofile:"+ planetDataFile);
	
}


	
	// Record planet name  typed by the user in an array.
	
	public void recordPlanets(){
		
		String planetName=dataField.getText();
		if(planetsRecorded<maxPlanets){
			planets[planetsRecorded]=planetName;
			planetsRecorded++;
		}

		
		dataField.setText("Next");
		saved=false;  // This data has not been saved.
		
	}// End of recordPlanets.
	
	// Save all planet names typed so far in the file named planetFile.
	
	public void writePlanetsToFile() throws IOException{
	
		// We will discuss  the try and catch statements during the
		// week starting Oct 25.
		
			if(saved){
				dataField.setText("Data already saved.");
				return;
			}else{
				fileWrite(planetDataFile);
				saved=true;
			}
	
	}
	
	// Erase file.
	
	public void eraseFile(String filename) throws IOException{
		
		dataField.setText("Please delete  file: "+filename+"  yourself.");
		
	}
	// Read and display planet names that are in the file.
	
	public void displayPlanets() throws IOException{
		
		fileReadAndDisplay(planetDataFile);
	}
	

public String getNextName(int len, DataInputStream in) throws IOException{
	
	char [] name=new char[maxNameLen];
	for (int i=0; i<len; i++){
		name[i]=in.readChar();
	}
	return(new String(name));  // Convert name array to a string and return.
}


// Get file name from the user.

public String getFileName(){

	if(fileNameSet)
		return(planetDataFile);

	else {
		fileNameSet=true;
		String fileName=dataField.getText();
		dataField.setText("File name recorded.");
		return(fileName);
	}
}

}
