/*
 * Inscoper NBO Example: Import NBO-XML
 * ====================================
 * This example demonstrates how to populate an NBO object tree from an XML string
 * or from an XML file, and how imported documents are validated.
 *
 * Prerequisites:
 * -------------
 * 1. Installation: inscoper-nbo-<version>.jar must be on the classpath.
 * 2. Sample Data: this example reads instrument_sample.xml. Change SAMPLE_PATH
 *    below to the location where you saved it.
 */

// --8<-- [start:main_logic]
import com.inscoper.nbo.Image;
import com.inscoper.nbo.Instrument;
import com.inscoper.nbo.Objective;

public class ImportXml {

    static final String SAMPLE_PATH = "instrument_sample.xml";

    public static void main(String[] args) {
        // Step 1: Import from a string
        // Importing replaces the whole content of the target object.
        Image image = new Image();

        image.fromXmlString("""
                <?xml version="1.0"?>
                <Image ID="Image:1" Name="Field 1">
                  <StageLabel Name="Position 0" X="0" Y="0" />
                  <StageLabel Name="Position 1" X="120.5" Y="0" />
                </Image>""");

        System.out.println(image.getID().get() + " " + image.getName().get());
        System.out.println(image.getStageLabel_List().size());

        // Step 2: Import from a file
        Instrument instrument = new Instrument();
        instrument.fromXmlFile(SAMPLE_PATH);

        System.out.println(instrument.getID().get());
        for (Objective objective : instrument.getObjective_List()) {
            System.out.println(objective.getModel() + " " + objective.getMagnification());
        }

        // Step 3: Imported documents are validated
        // Values that violate the schema restrictions throw
        // InscoperNBOValidationException, which keeps invalid metadata out of the model.
        String nonCompliant = """
                <?xml version="1.0"?>
                <Image ID="NotAnImageIdentifier" />""";

        try {
            image.fromXmlString(nonCompliant);
        } catch (Exception error) {
            System.out.println("Rejected document: " + error.getMessage());
        }

        // Pass false to import a non-compliant document as it is
        image.fromXmlString(nonCompliant, false);
        System.out.println(image.getID().get());
    }
}
// --8<-- [end:main_logic]
