/*
 * @(#)FileMonitor.java
 *
 * Copyright (c) 2002-2003 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 */

package com.jscape.file;

import java.io.File;

/**
 * Monitors a file for changes.
 */
public class FileMonitor {

    /**
     * To check whether file monitor is running.
     */
    private boolean running = false;
    /**
     * The file to monitor.
     */
    private File file;
    /**
     * A thread to for file monitor.
     */
    private FileMonitorThread monitor;

    /**
     * Monitor delay.
     */
    private int delay;

    /**
     * Creates a new <code>FileMonitor</code> instance.
     *
     * @param file  the file to monitor
     * @param delay the frequency in seconds to check the file for changes
     */
    public FileMonitor(final File file, final int delay) {
        this.file = file;
        this.delay = delay;
    }

    /**
     * Starts this <code>FileMonitor</code>.
     */
    public void start() {
        synchronized (this) {
            if (!running) {
                monitor = new FileMonitorThread();
                monitor.start();
            }
        }
    }

    /**
     * Stops this <code>FileMonitor</code>.
     */
    public void stop() {
        running = false;
    }

    /**
     * Thread for monitoring file.
     */
    class FileMonitorThread
            extends Thread {

        /**
         * Process for checking for file modifications.
         */
        public void run() {
            running = true;
            long timestamp = file.lastModified();

            while (true) {
                if (!running) {
                    return;
                }
                System.out.println("Checking file");
                try {
                    if (file.exists()) {
                        long tmp = file.lastModified();
                        if (tmp != timestamp) {
                            timestamp = tmp;
                            System.out.println("!!!File has been modified!!!");
                        }
                    } else {
                        System.out.println("!!!File no longer exists!!!");
                        running = false;
                        return;
                    }
                    Thread.sleep(delay);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        }
    }
}
