package usda.weru.remoteDataAccess.csip.polygon.soil;

import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import usda.weru.remoteDataAccess.RdaHierarchicalItem;
import usda.weru.remoteDataAccess.RdaInputController;
import usda.weru.remoteDataAccess.csip.CsipInputControllerCacheLoader;
import usda.weru.remoteDataAccess.csip.CsipInputControllerCachingSupport;
import usda.weru.remoteDataAccess.csip.polygon.CsipInputContPolygon;
import usda.weru.remoteDataAccess.exceptions.RdaConnectException;

/**
 *
 * @author mhaas
 */
public class CsipInputContSoilCacheLoader extends CsipInputControllerCacheLoader {
       
    private static final Logger LOGGER = LogManager.getLogger(CsipInputContSoilCacheLoader.class);

    public CsipInputContSoilCacheLoader (RdaInputController controllerCache, CsipInputControllerCachingSupport cacheSupport) {
        super(controllerCache, cacheSupport);
    }
        
    @Override
    protected boolean checkIdxFileForSkip() {
        return false;
    }
        
    protected String checkIdxFileMakePolyStr() {
        String s = "";
        ArrayList<Point2D.Double> poly = ((CsipInputContPolygon)rdaControllerCache).getPolygon();
        if (poly != null) {
            for (Point2D.Double p : poly) {
                s = s + p.getX() + ',' + p.getY() + ';';
            }
        }
        return s;
    }
    
    @Override
    protected void writeIdxComplete (File idxFile, String serviceName) {
        try {
            String polyGonsStr = checkIdxFileMakePolyStr();
//            writeIdxFile (idxFile, "Complete:"+LocalDate.now().toString());
            appendIdxFile (idxFile, "Complete:"+LocalDate.now().toString());

            // keep list of all polygons, to show in MapViewer
            String polyname = idxFile.getName();
            polyname = polyname.replace(".idx", ".polygons");
            File polyFile = new File (idxFile.getParentFile(), polyname);
            appendIdxFile (polyFile, "Polygon:" + polyGonsStr + "\n");
        } catch (IOException ex) {
            LOGGER.log(Level.INFO,
                "Cache " + serviceName + " fail updating idx file: " + idxFile.getAbsolutePath());
        }
        
    }
    
    @Override
    protected void cacheSingleFile (RdaHierarchicalItem fileItem, File cacheFile, File idxFile) throws RdaConnectException, IOException {
        File csipFile = null;

        if ( ((CsipInputContSoilCachingSupport)cachingSupport).getCsipCachedFile(fileItem) == null) {
            // MEH
            // WEPS soils filename is not known until the file is downloaded and parsed.
            // (Some filename components come from the parsed soil file elements)
            // To avoid confusion for the user, soils are downloaded to a somewhat hidden temp dir,
            // then parsed, then moved to the soils cache dir when the final file name is known.
            String parent = cacheFile.getParent();
            parent = parent.replace("Soils", "SoilsTmp");
            File cacheFileParent = new File (parent);
            cacheFileParent.mkdirs();
            //cacheFile.getParentFile().mkdirs();
            //rdaControllerCache.controllerSetDestinationPath( cacheFile.getParentFile().toPath() );
            rdaControllerCache.controllerSetDestinationPath( cacheFileParent.toPath() );

            String csipPath = fileItem.getParentPath();
            String name = fileItem.getName();

            try {
                csipFile = doCallCsipGetRecord(name, csipPath);
            } catch (RdaConnectException ex) {                
                ((CsipInputContSoilCachingSupport)cachingSupport).deleteFailedDownloadFiles(fileItem);
                throw (ex);
            }

            ((CsipInputContSoilCachingSupport)cachingSupport).moveCsipFileToCache(fileItem, csipFile);
            
        } else {
            System.out.println (" already in cache:" + cacheFile);
        }
    }
}
