/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/11/21 12:01:46
!  AUTHOR(S): KOGA, Junichiro
!  File : Tail.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */
package ciss.phase_viewer.common;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import org.apache.log4j.Logger;

/**
 * 
 */
public class Tail extends TimerTask {
    private int numLines = 10; /* プリントする行数 */

    private long fileLength = Long.MAX_VALUE; /* ファイルの長さ */

    private long lastModified = 0L; /* ファイルが最後にいつ更新されたか */

    private long period = 1000L;

    private File file;

    private OutputStream out;

    private Timer timer;

    private Logger logger = Logger.getLogger(Tail.class.getName());

    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            System.out.println("usage: java Tail fileName");
            System.exit(0);
        }
        Tail tail = new Tail(new File(args[0]), System.out);
        tail.doIt();
    }

    public Tail(File file, OutputStream out) {
        this.file = file;
        this.out = out;
    }

    public void doIt() {
        timer = new Timer();
        timer.schedule(this, 0L, period);
    }

    public void kill() {
        cancel();
        timer = null;
    }

    private void initTail(BufferedReader reader) throws IOException {
        String line = "";
        Vector vec = new Vector();
        while ((line = reader.readLine()) != null)
            vec.add(line);
        String[] big = new String[vec.size()];
        vec.copyInto(big);
        lastModified = file.lastModified();
        int len = big.length - numLines;
        if (len < 0)
            len = 0;
        for (int i = len; i < big.length; i++) {
            out.write(big[i].getBytes());
            out.write(System.getProperty("line.separator").getBytes());
        }
        fileLength = file.length();
        initialized = true;
    }

    private boolean initialized = false;
    private final byte[] ls = System.getProperty("line.separator").getBytes();

    public void run() {
        BufferedReader reader = null;
        try {
            if (!file.exists())
                return;
            reader = new BufferedReader(new FileReader(file));

            long currFileLength = file.length();
            // logger.info("currFileLength, fileLength : "+currFileLength+" "+fileLength);
            if (fileLength > currFileLength && !initialized)
                initTail(reader);

            // if (file.lastModified() == lastModified)
            // return;
            if (currFileLength == fileLength)
                return;
            String line = "";
            Vector vec = new Vector();
            reader.skip(fileLength);
            while ((line = reader.readLine()) != null)
                vec.add(line);
            if (vec.size() == 0)
                return;
            for (int i = 0; i < vec.size(); i++) {
                out.write(vec.get(i).toString().getBytes());
                out.write(ls);
            }

            if (out instanceof BufferedOutputStream)
                ((BufferedOutputStream) out).flush();

            fileLength = currFileLength;
            lastModified = file.lastModified();
        } catch (IOException ioe) {
            logger.error("failed ...");
            ioe.printStackTrace();
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException ioe) {
            }
        }
    }

}
