/*
 * DirectoryResource.java
 *
 * Created on September 27, 2001, 4:19 PM
 */

package org.apache.avalon.excalibur.monitor;

import java.io.File;

/**
 *
 * @author  mtoma
 * @version 
 */
public class DirectoryResource extends Resource {
    
    private final File m_file;
    private int count;
    private int hash;
    private long modified;

    /**
     * Instantiate the FileResource
     */
    public DirectoryResource( String resource )
        throws Exception
    {
        this( new File( resource ) );
    }

    public DirectoryResource( File resource )
        throws Exception
    {
        super( resource.getCanonicalPath() );
        
        if ( resource.isFile() ) throw new Exception("Resource is not a directory");
        
        m_file = resource;        
        modified = System.currentTimeMillis();        
        count = count( m_file );
        hash = hash( m_file );
    }
    
    public long lastModified()
    {        
        if ( (count != count( m_file ) ) || ( hash != hash( m_file ) ) ) 
        {
            count = count( m_file );
            hash = hash( m_file );
            modified = System.currentTimeMillis();
        }
        
        return modified;
    }
    
    private int count( final File directory )
    {
        final File[] list =  m_file.listFiles();
        int files = 0;
        
        if ( null != list ) 
        {
            files = list.length;

            for ( int i = 0; i < list.length; i++ )
            {
                files += count( list[i] );
            }   
        }
        
        return files;            
    }
    
    private int hash( final File directory )
    {        
        final File[] list =  m_file.listFiles();
        int hash = directory.hashCode();        
        
        if ( null != list ) 
        {
            for ( int i = 0; i < list.length; i++ )
            {
                hash ^= list[i].hashCode();
            }
        }
        
        return hash;
    }   
}
