/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package component.spring;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;

@ManagedResource(description="Directory Scanner Component.",
objectName="demo.integration:name=DirectoryScanner,type=SpringComponent")
public class DirectoryScanner implements Controllable{
    private static Log log = LogFactory.getLog(DirectoryScanner.class);
    private File location;
    private boolean started;
    private FileListFilter fileFilter;
    
    @ManagedAttribute(description="Comma separated list of file extension to scan for.")
    public String getExtensionList() {
        return (fileFilter != null) ? fileFilter.toString() : null;
    }
    
    @ManagedAttribute
    public void setExtensionList(String extensionList) {
        fileFilter = new FileListFilter(extensionList);
    }

    @ManagedAttribute(description="The directory location to scan.")
    public String getLocation() {
        return (location != null) ? location.getPath() : null;
    }

    @ManagedAttribute
    public void setLocation(String location) {
        this.location = new File(location);
    }
   
    public void scan() throws RuntimeException {
        if (started) {
            if (location != null && location.isDirectory()) {
                File[] list = location.listFiles(fileFilter);
                log.info("Scanned [" + list.length + "] files with extensions [ " + fileFilter.toString() + "]" +
                        " from [" + location.getAbsolutePath() + "]");
            } else {
                log.warn("Unable to scan location [" + location.getAbsolutePath() + "].  Make sure it's valid.");
            }
        }
    }
   
    @ManagedOperation(description="Lifecycle to start component.")
    public void start() {
        started = true;
        log.info("**** Directory Scanner Compoennt started OK.");
    }

    @ManagedOperation(description="Lifecycle to stop component.")
    public void stop() {
        started = false;
        log.info("**** Directory Scanner Compoennt stopped OK.");
    }
    
    private class FileListFilter implements FileFilter {
        private String filters;
        
        public FileListFilter(String filters){
            this.filters = filters;
        }
        
        @Override
        public String toString() {
            return filters;
        }

        public boolean accept(File path) {
            return (filters.equals("*") && path.isFile()) ? true : path.getName().contains(filters);
        }
        
    }
}
