// Oefening ReadRandomFile, D&D 5, blz 880,..

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.DecimalFormat;
import javax.swing.*;

import be.hogent.h17.H17_BankUI;
import be.hogent.h17.H17_AccountRecord;
import be.hogent.h17.H17_RandomAccessAccountRecord;

public class H17_ReadRandomFile extends JFrame {
	
	private RandomAccessFile input;
	private H17_BankUI userInterface;
	private JButton nextButton, openButton;
	
	private static DecimalFormat twoDigits = new DecimalFormat("0.00");
	
	public H17_ReadRandomFile() {
		
		super ("Klantenbestand lezen");
		
		userInterface = new H17_BankUI(4);
		getContentPane().add(userInterface);
		
		openButton = userInterface.getDoTask1Button();
		openButton.setText("Bestand openen..");
		
		openButton.addActionListener(
			new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					openFile();
				}
			}
		);
		
		nextButton = userInterface.getDoTask2Button();
		nextButton.setText("Next");
		nextButton.setEnabled(false);
		
		nextButton.addActionListener(
			new ActionListener() {
				public void actoinPerformed(ActionEvent event) {
					readRecord();
				}
			}
		);
		
		addWindowListener(
			new WindowAdapter() {
				public void windowClosing (WindowEvent event) {
					closeFile();
				}
			}
		);
		
		setSize(300,150);
		setVisible(true);
	}
	
	private void openFile() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		int result = fileChooser.showOpenDialog(this);
		
		if (result == JFileChooser.CANCEL_OPTION)
			return;
		
		File fileName = fileChooser.getSelectedFile();
		
		if (fileName == null || fileName.getName().equals(""))
			JOptionPane.showMessageDialog(this, "Ongeldige bestandsnaam","Error",JOptionPane.ERROR_MESSAGE);
		else {
			try {
				input = new RandomAccessFile(fileName, "r");
				nextButton.setEnabled(true);
				openButton.setEnabled(false);
			}
			catch (IOException ioException) {
				JOptionPane.showMessageDialog(this, "Het gekozen bestand bestaat niet","Error",JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private void readRecord() {
		H17_RandomAccessAccountRecord record = new H17_RandomAccessAccountRecord();
		
		try {
			do {
				record.read(input);
			} while (record.getAccount() == 0);
			
			String values[] = { String.valueOf(record.getAccount()),record.getFirstName(),record.getLastName(),	String.valueOf(record.getBalance()) };
			
			userInterface.setFieldValues(values);
		}
		catch (EOFException eofException) {
			JOptionPane.showMessageDialog(this, "Geen records meer","Error",JOptionPane.ERROR_MESSAGE);
			closeFile();
		}
		catch (IOException ioException) {
			JOptionPane.showMessageDialog(this, "Fout bij het lezen van bestand","Error",JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void closeFile() {
		try {
			if (input != null)
				input.close();
			
			System.exit(0);
		}
		
	}
	
}
