package ucar.nc2.image;

import ucar.nc2.adde.AddeImage;

import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.File;
import java.util.List;

import thredds.catalog.*;

/**
 * Created by IntelliJ IDEA.
 * User: john
 * Date: Aug 23, 2004
 * Time: 5:18:17 PM
 * To change this template use File | Settings | File Templates.
 */
public class ImageDatasetFactory {

  private StringBuffer log;
  public String getErrorMessages() { return log == null ? "" : log.toString(); }

  public BufferedImage open( String location) throws java.io.IOException {
    log = new StringBuffer();

    if (location.startsWith("adde:")) {

      try {
        AddeImage addeImage = AddeImage.factory( location);
        return addeImage.getImage();
      } catch (Exception e) {
        log.append(e.getMessage());
        // e.printStackTrace();
        return null;
      }

    }

    else if (location.startsWith("http:")) {
      try {
        URL url = new URL(location);
        return javax.imageio.ImageIO.read(url);

      } catch (MalformedURLException e) {
        log.append(e.getMessage());
        //e.printStackTrace();
        return null;
      } catch (IOException e) {
        log.append(e.getMessage());
        //e.printStackTrace();
        return null;
      }
    }

    else  {
      if (location.startsWith("file:)"))
        location = location.substring(5);

      try {
        File f = new File(location);
        if (!f.exists()) {
          return null;
        }

        return javax.imageio.ImageIO.read(f);

      } catch (MalformedURLException e) {
        log.append(e.getMessage());
        //e.printStackTrace();
        return null;
      } catch (IOException e) {
        log.append(e.getMessage());
        //e.printStackTrace();
        return null;
      }
    }
  }

}
