/*
 * $Id: Ex1.java,v 1.1.1.1 2005/09/23 20:24:11 norman Exp $
 *
 * Copyright (c) 2005 by Brockmann Consult GmbH. All right reserved.
 * http://www.brockmann-consult.de
 */
package org.esa.beam.basics;

import org.esa.beam.framework.dataio.ProductIO;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.util.logging.BeamLogManager;

import java.io.IOException;

/**
 * This exercise shows how to
 * <ol>
 * <li>obtain a <code>Product</code> object from a file path</li>
 * <li>use the <code>ProductIO</code> class to open a data product and perform naive I/O error handling</li>
 * <li>query a few <code>Product</code> properties</li>
 * <li>output the property values to the console</li>
 * <li>close underlying product I/O and dispose the <code>Product</code> object</li>
 * <li>get rid of the BEAM console logging</li>
 * <li>close product I/O and dispose the product object</li>
 * </ol>
 */
public class Ex1 {
    /**
     * The program entry point.
     *
     * @param args must be of length 1. <code>args[0]</code> contains the product file path
     */
    public static void main(String[] args) {
        // get rid of the console logging
        BeamLogManager.removeRootLoggerHandlers();

        // obtain a Product object from a file path
        String filePath = args[0];
        Product product = readProduct(filePath);

        // query a few <code>Product</code> properties
        String name = product.getName();
        int width = product.getSceneRasterWidth();
        int height = product.getSceneRasterHeight();
        ProductData.UTC time = product.getSceneRasterStartTime();

        // output the property values to the console
        System.out.printf("product %s:\n" +
                "  raster size is %d x % d pixels,\n" +
                "  sensing started %s\n",
                          name, width, height, time);

        // close product I/O and dispose the product object
        product.dispose();
    }

    /**
     * Reads a product. If an error occurs, <code>System.exit</code> is called with an error code.
     *
     * @param filePath the product file path
     * @return the product object, never null
     */
    public static Product readProduct(String filePath) {
        Product product = null;
        try {
            // Use the ProductIO class to open a data product
            product = ProductIO.readProduct(filePath, null);
        } catch (IOException e) {
            // perform naive I/O error handling
            System.out.printf("Error: failed to open file %s: %s\n", filePath, e.getMessage());
            System.exit(1);
        }
        if (product == null) {
            // perform naive I/O error handling
            System.out.printf("Error: no reader found for file %s\n", filePath);
            System.exit(2);
        }
        return product;
    }
}

