package usda.weru.util.tree;

import de.schlichtherle.truezip.file.TFile;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Comparator;
import org.apache.commons.io.FileUtils;
import usda.weru.remoteDataAccess.csip.CsipInputControllerStatic;
import usda.weru.remoteDataAccess.csip.polygon.soil.CsipInputContSoilBgCache;
import usda.weru.remoteDataAccess.csip.polygon.soil.CsipInputContSoilCachingSupport;
import usda.weru.util.ConfigData;

/**
 *
 * @author mhaas
 */
public class WepsTreeNodeFileSoilCache extends WepsTreeNodeFile {

    private static final long serialVersionUID = 1L;
    
    CsipInputContSoilCachingSupport cacheSupport;
    CsipInputContSoilBgCache controller;
    
    public WepsTreeNodeFileSoilCache(TFile file, FileFilter filter) {
        this(file, filter, null);
    }
    
    public WepsTreeNodeFileSoilCache(TFile file, FileFilter filter, Comparator<TFile> comparator) {
        super(file, filter, comparator);
        
//        controller = new CsipInputContSoilBgCache();
        controller = (CsipInputContSoilBgCache)CsipInputControllerStatic.getSoilController();
//        cacheSupport = new CsipInputContSoilCachingSupport (controller);
        cacheSupport = controller.getCachingSupport();
    }
    
    public WepsTreeNodeFileSoilCache(WepsTreeNodeFile nodetoCopy, WepsTreeNodeFileSoilCache existingNode) {
        super (nodetoCopy.file, nodetoCopy.filter, nodetoCopy.comparator);
        controller = existingNode.controller;
        cacheSupport = existingNode.cacheSupport;
    }
    
    @Override
    public TFile getNodeData() {
        //System.out.println("This is the CSIP cache");
        if (this.isLeaf()) {
            String destFileName = file.getName();
            destFileName = cacheSupport.updateName(destFileName);
            TFile destFile = new TFile (ConfigData.getDefault().getData(ConfigData.CurrentProj), destFileName);

            try {
                FileUtils.copyFile(file, destFile, true);
            } catch (IOException ex) {
                destFile = file;
            }
           return destFile;
        }
        return file;
    }
    
    @Override
    protected WepsTreeNodeFileSoilCache createChild(TFile file, FileFilter filter, Comparator<TFile> comparator) {
        WepsTreeNodeFile child = super.createChild(file, filter, comparator);
        return new WepsTreeNodeFileSoilCache(child, this);
    }
}
