package com.limegroup.gnutella.malware;

import java.io.File;
import java.util.Locale;

import org.limewire.inject.LazySingleton;
import org.limewire.logging.Log;
import org.limewire.logging.LogFactory;
import org.limewire.util.FileUtils;

import com.google.inject.Inject;

/**
 * Compares the mime type of a file to its extension to ensure that, if the
 * mime type indicates a dangerous file type, the extension is one of those
 * allowed for the file type.
 */
@LazySingleton
class FileExtensionChecker implements DangerousFileChecker {

    private static final Log LOG =
        LogFactory.getLog(FileExtensionChecker.class);

    private final MimeTypeEncoder mimeTypeEncoder;
    private final DangerousFileTypeEncoder dangerousFileTypeEncoder;

    @Inject
    FileExtensionChecker(MimeTypeEncoder mimeTypeEncoder,
            DangerousFileTypeEncoder dangerousFileTypeEncoder) {
        this.mimeTypeEncoder = mimeTypeEncoder;
        this.dangerousFileTypeEncoder = dangerousFileTypeEncoder;
    }

    /**
     * Returns true if the file's mime type indicates a dangerous type
     * but the extension does not.
     */
    @Override
    public boolean isDangerous(File file) {
        if(LOG.isDebugEnabled())
            LOG.debug("Checking " + file);
        // Get the mime type (null if it's unknown)
        String mimeType = mimeTypeEncoder.getMimeType(file);
        if(mimeType == null) {
            LOG.debug("Unknown mime type");
            return false;
        }
        // Get the extension (empty if there's no extension)
        String ext = FileUtils.getFileExtension(file).toLowerCase(Locale.US);
        if(LOG.isDebugEnabled())
            LOG.debug(ext.isEmpty() ? "No extension" : "Extension " + ext);
        // Check whether the extension is allowed for the mime type
        return !dangerousFileTypeEncoder.isAllowed(mimeType, ext);
    }
}
