package org.spview.gui;
/*
 * Class to show a text file content
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/////////////////////////////////////////////////////////////////////

/**
 * Window to show a text file content.
 */
public class JFFileOut extends JFrame implements Runnable {

    /**
	 * 
	 */
	private static final long serialVersionUID = 6788894636251358665L;
	private String nfil;                                             // file name
    // panels
    private JPanel pcentre;

    // to show the string array
    private JScrollPane jsp;                                         // with lifts
    private JTextArea   jta;

    // thread
    private volatile Thread threadThis;                              // volatile for clean exit

    private String lnsep;                                            // line separator
    private Font mono14;                                             // Monospaced 14 font

/////////////////////////////////////////////////////////////////////

    /**
     * Constructs a JFFileOut.
     *
     * @param cnfil     file name
     * @param cp_x      x location of frame
     * @param cp_y      y location of frame
     */
    public JFFileOut( String cnfil, int cp_x, int cp_y ) {

        super(cnfil);                                                // main window

        addWindowListener(new WindowAdapter() {                      // clean end
            public void windowClosing(WindowEvent e) {
                threadThis = null;                                   // clean exit flag
                dispose();                                           // free window
            }
        });
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        if( cnfil.trim().length() == 0 ) {
            // empty file name
            dispose();
            return;
        }
        nfil = cnfil;                                                // file name

        mono14 = new Font("Monospaced", Font.PLAIN, 14);
        lnsep = System.getProperty("line.separator");

        getContentPane().setLayout(new BorderLayout());
        JPanel jp = new JPanel(new BorderLayout());
        jp.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLUE,4),null));
        getContentPane().add(jp,"Center");

        // panels
        pcentre = new JPanel();

        // center
        jta = new JTextArea();
        jta.setColumns(70);                                          // jta width
        jta.setBackground(Color.BLACK);
        jta.setForeground(Color.WHITE);
        jta.setEditable(false);                                      // not editable
        jta.setFont( mono14 );
        jta.setLineWrap(false);                                      // no line wrap
        jta.setRows(10);                                             // nb of lines
        jsp = new JScrollPane(jta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);  // with lifts
        pcentre.add(jsp);

        // insert panels
        jp.add(pcentre,"Center");

        // launch thread for read and display file
        threadThis = new Thread(this);                                  // set thread (run of this instance)
        threadThis.start();                                          // launch it

        setLocation( cp_x/2, cp_y/2 );
        pack();
    }

    /**
     *  Thread launched by start.
     *  <br>Wait for file to exist
     *  <br>Display it's content while it grows
     */
    public void run() {

        // file read variables
        FileReader     fr;
        BufferedReader br;
        File           ffil;
        String         str;

        Thread currenT = Thread.currentThread();                     // get current thread
        // wait for file to exist
        jta.append("Please, wait ");
        ffil = new File(nfil);
        while( ! ffil.exists() ) {
            // window closed ?
            if( threadThis != currenT ) {
                // yes, exit
                return;
            }
            try{
                //wait(1000);
                Thread.sleep(1000);                                  // every second
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }
            jta.append(".");
        }
        jta.setText("");                                             // empty text area
        // read file as it grows
        try {
            fr = new FileReader( ffil );
            br = new BufferedReader( fr );
            while( true ) {                                          // indefinitly
                // window closed ?
                if( threadThis != currenT ) {
                    // yes, clean exit
                    br.close();                                      // free file access
                    return;
                }
                if( (str = br.readLine()) != null ) {
                    // some line to display
                    jta.append(str+"\n");
                }
                else {
                    try{
                        //wait(1000);
                        Thread.sleep(1000);                          // every second
                    }
                    catch(InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
		catch (IOException ioe) { // IO error
			JOptionPane.showMessageDialog(null, "IO error while reading file" + lnsep + ffil + lnsep + ioe);
		}
    }

}
