
package usda.weru.remoteDataAccess.remoteFiles;

import de.schlichtherle.truezip.file.TFile;
import ex1.NotePrinter;
import java.io.File;
import java.lang.reflect.Constructor;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 *
 * @author mhaas
 */
public  class WepsBaseFile extends File {
    
    static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LogManager.getLogger(WepsBaseFile.class);
    
    public WepsBaseFile() {
        this("");
    }
    public WepsBaseFile(String file) {
        super(file);
    }
    public WepsBaseFile(String parent, String file) {
        super(parent, file);
    }    
    public WepsBaseFile(File parent, String child) {
        super(parent, child);
    }
  
    //
    // Helper method
    // Returns a new file objectparent + child.
    // Return type is the type of the parent (File, TFil, or one of the sub types based on this class)
    //
    public static File newOfParentType (File f, String name) {
        try {
            //
            // Look for a constructor that is (File, String) first.  This is our preference and is required for
            //  the subclasses of this class.
            // However, this code also works with TFile class, which does not have a (Tfile, String) constructor.
            //  It has (File, String) but not (TFile, String).
            // Default is (String, String) which works fine for TFile.
            //
            for (Constructor<?> cc : f.getClass().getConstructors()) {
                if (cc.getParameterCount()== 2) {
                    if ((cc.getParameters()[0].getType() == f.getClass()) && (cc.getParameters()[1].getType() == String.class) ) {
                        return (File) f.getClass().getConstructor(f.getClass(),String.class).newInstance(f,name);
                    }
                }
            }
            
            return (File) f.getClass().getConstructor(String.class,String.class).newInstance(f.getPath(),name);
        } catch (Exception ex) {
            LOGGER.log(Level.ERROR, ex.getMessage());
        }
        return null;
    }
    
    @Override
    public boolean isDirectory () {
        // Use TFile so that we can descend into zips, etc.
        TFile testFile = new TFile (this.getAbsolutePath());
        return testFile.isDirectory(); // for an archive, TFile returns true for both isFile and isDir. Here we care if it is a dir or not.
    }
    
    @Override
    public boolean isFile () {
        return ! isDirectory();
    }
    
    public boolean isDirectoryActual () {
        return super.isDirectory();
    }
    
    @Override
    public File getParentFile()
    {
        return super.getParent() == null ? null : (File)new WepsBaseFile (super.getParent());
    }
    
}
