/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.deployment.annotation.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.Set;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.jar.JarFile;
import java.util.jar.JarEntry;

import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import com.sun.enterprise.deployment.annotation.Scanner;
import com.sun.enterprise.deployment.annotation.impl.JavaEEScanner;
import com.sun.enterprise.deployment.annotation.introspection.ClassFile;

/**
 * This is an abstract class of the Scanner interface for J2EE module.
 *
 * @author Shing Wai Chan
 */
abstract class ModuleScanner extends JavaEEScanner implements Scanner {
    protected File archiveFile = null;
    protected ClassLoader classLoader = null;
    protected ClassFile classFile = new ClassFile();
    private boolean processAllClasses = Boolean.getBoolean("com.sun.enterprise.deployment.annotation.processAllClasses");

    
    private Set<String> entries = new HashSet<String>();

    /**
     * This add extra className to be scanned.
     * @param className
     */
    protected void addScanClassName(String className) {
        if (className!=null && className.length()!=0)
            entries.add(className);
    }

    /**
     * This add all classes in given jarFile to be scanned.
     * @param jarFile
     */
    protected void addScanJar(File jarFile) throws IOException {
        JarFile jf = new JarFile(jarFile);
        

        Enumeration<JarEntry> entriesEnum = jf.entries();
        while(entriesEnum.hasMoreElements()) {
            JarEntry je = entriesEnum.nextElement();
            if (je.getName().endsWith(".class")) {
                if (processAllClasses) {
                    addEntry(je);
                } else {
                    // check if it contains top level annotations...
                    ReadableByteChannel channel = Channels.newChannel(jf.getInputStream(je));
                    if (channel!=null) {
                        if (classFile.containsAnnotation(channel, je.getSize())) {
                            addEntry(je);                     
                        }
                    }
                }
            }
        }
    }
    
    private void addEntry(JarEntry je) {
        String className = je.getName().replace('/', '.');
        className = className.substring(0, className.length()-6);
        entries.add(className);                                
    }
    
    private void addEntry(File top, File f) {
        String fileName = f.getPath();
        fileName = fileName.substring(top.getPath().length()+1);
        String className = fileName.replace(File.separatorChar, '.');
        className = className.substring(0, className.length()-6);
        entries.add(className);        
    }

    /**
     * This will include all class in directory to be scanned.
     * param directory
     */
    protected void addScanDirectory(File directory) throws IOException {
        initScanDirectory(directory, directory);
    } 
    
    private void initScanDirectory(File top, File directory) throws IOException {
   
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                String fileName = file.getPath();
                if (fileName.endsWith(".class")) {
                    if (processAllClasses) {
                        addEntry(top, file);
                    } else {
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(file);
                            if (classFile.containsAnnotation(fis.getChannel(), file.length())) {
                                addEntry(top, file);
                            }
                        } finally {
                            if (fis != null) {
                                fis.close();
                            }
                        }
                    }
                }
            } else {
                initScanDirectory(top, file);
            }
        }
    }

    public ClassLoader getClassLoader() {
        return classLoader;
    }

    public Set<Class> getElements() {
        Set<Class> elements = new HashSet<Class>();
        if (getClassLoader() == null) {
            AnnotationUtils.getLogger().severe("Class loader null");
            return elements;
        }        

        for (String className : entries) {
            if (AnnotationUtils.getLogger().isLoggable(Level.FINE)) {
                AnnotationUtils.getLogger().fine("Getting " + className);
            }
            try {                
                elements.add(classLoader.loadClass(className));
            } catch(Throwable cnfe) {
                AnnotationUtils.getLogger().warning("Cannot load " + className + " reason : " + cnfe.getMessage());
            }
        }
        return elements;
    }
}
