package ucar.nc2.thredds;

import ucar.ma2.*;
import ucar.nc2.*;
import ucar.nc2.adde.AddeDatasetFactory;
import ucar.nc2.adde.AddeImage;
import ucar.nc2.dods.DODSNetcdfFile;
import ucar.nc2.dataset.NetcdfDataset;

import thredds.catalog.*;

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

import dods.dap.DODSException;

/**
 * This opens a URL that refers to a dataset in a THREDDS catalog, and gets the thredds InvDataset object.
 * It examines the possible InvAccess objects, and choses one that it knows how to open as a NetcdfDataset.
 * It annotates the NetcdfDataset with info from the InvDataset.
 *
 * Valid URLS:
 *  thredds:http://localhost:8080/test/addeStationDataset.xml#surfaceHourly (on-line)
 *  thredds://localhost:8080/test/addeStationDataset.xml#surfaceHourly (http is added)
 *  thredds:file:///c:/dev/netcdf-java-2.2/test/data/catalog/addeStationDataset.xml#AddeSurfaceData (absolute file)
 *  thredds:file:test/data/catalog/addeStationDataset.xml#AddeSurfaceData (reletive file)
 */
public class ThreddsImageFactory {
  static private String threddsServer = "http://motherlode.ucar.edu:8080/thredds/";
  static private boolean debugOpen = true;

  private InvCatalogFactory catFactory = new InvCatalogFactory("", false);
  private StringBuffer log;
  public String getErrorMessages() { return log == null ? "" : log.toString(); }

  public BufferedImage openImage( 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;
      }
    }
  }

}
