package skyview.survey;


import java.io.File;
import skyview.executive.Settings;
import skyview.survey.CachingImageFactory;
import skyview.survey.FitsImage;
import skyview.survey.Image;
import skyview.survey.ImageFactory;

/** This class is used by the CachingImageFactory to actually get
 *  the images over the net.
 * @author tmcglynn
 */

class URLRetrieverFactory implements ImageFactory {
    
    static private java.util.regex.Pattern comma = java.util.regex.Pattern.compile(",");
    private static String subdir = null;
    
    public static String getWriteCache() {
	String[] caches = Settings.getArray("Cache");
	if (caches.length == 0) {
	    caches = new String[]{CachingImageFactory.DFT_CACHE};
	}
	
	String cache = caches[0];
	
	if (subdir != null) {
	    cache += subdir+File.separatorChar;
	}
	    
	
	File dir = new File(cache);
	if (!dir.exists()) {
	    try {
		dir.mkdirs();
	    } catch (Exception e) {
		System.err.println("Error creating cache:"+caches[0]);
		throw new Error("Error: Unable to create cache directory");
	    }
	}
        return cache;
    }
    
    public Image factory(String spell) {
	
	String[] tokens = comma.split(spell);
        String file =null;
	try {
	    // Retrieve to temporary name and rename only after
	    // successful retrieval.
            System.err.println("   Retrieving remote URL: "+tokens[0]);
            Cacher cache = new Cacher();
            file = cache.cacheRemoteURL(tokens[0],tokens[1]);
	    return new FitsImage(file);
	} catch (Exception e) {
            System.err.println("Retrieval error");
            e.printStackTrace(System.err);
            String warning = "";
            if (Settings.has("_warning")) {
                warning += Settings.get("_warning")+"<br>";                    
            }
            warning += "Remote access error for file:"+file;
            Settings.put("_warning", warning);
            System.err.println("Setting warning:"+warning);
	    throw new Error("Error, "+e+",  retrieving URL to file:"+tokens[0]);
	}
    }     
}
