package ucar.nc2.station;

import ucar.nc2.*;
import ucar.nc2.dataset.*;
import ucar.nc2.adde.AddeStationDataset;
import ucar.nc2.thredds.DqcStationObsDataset;
import thredds.catalog.query.DqcFactory;
import thredds.catalog.query.QueryCapability;
import thredds.catalog.InvDataset;
import thredds.catalog.InvAccess;
import thredds.catalog.ServiceType;

/**
 * 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 StationDatasetFactory {

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

  public StationObsDataset open(InvAccess access) throws java.io.IOException {
    log = new StringBuffer();

    if (access.getService().getServiceType() == ServiceType.ADDE)
      return new AddeStationDataset(access, null);

    return null;
  }

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

    if (location.startsWith("adde:"))
      return new AddeStationDataset( location, null);

    if (location.startsWith("thredds:")) {
      location = location.substring(8);
      DqcFactory dqcFactory = new DqcFactory(true);
      QueryCapability dqc = dqcFactory.readXML(location);
      if (dqc.hasFatalError()) {
        log.append(dqc.getErrorMessages());
        return null;
      }

      return DqcStationObsDataset.factory( dqc);
    }

    // otherwise open as netcdf dataset and have a look
    // note we open so that the record variables are made into a structure.
    boolean saveMode = NetcdfFile.getUseRecordStructure();
    NetcdfFile.setUseRecordStructure( true);
    NetcdfFile ncfile = NetcdfDataset.openFile( location, null); // LOOK why not a dataset ?
    NetcdfFile.setUseRecordStructure( saveMode);

    if (ncfile instanceof AddeStationDataset)
      return (AddeStationDataset) ncfile;

    if (UnidataStationObsDataset.isValidFile( ncfile))
      return new UnidataStationObsDataset( ncfile);

    if (CoardsStationObsDataset.isValidFile( ncfile))
      return new CoardsStationObsDataset( ncfile);

    if (MadisStationObsDataset.isValidFile( ncfile))
      return new MadisStationObsDataset( ncfile);

    if (OldUnidataStationObsDataset.isValidFile(ncfile))
      return new OldUnidataStationObsDataset( new NetcdfDataset(ncfile));

    return null;
  }

}
