/*
 * 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: the include directory of the release must be on the include
 *    paths, and the application must link against the NBO library.
 * 2. Sample Data: this example reads instrument_sample.xml. Change SAMPLE_PATH
 *    below to the location where you saved it.
 */

// --8<-- [start:main_logic]
#include <NBO/NBO/Image.h>
#include <NBO/NBO/Instrument.h>
#include <NBO/Shared/Exception/InscoperNBOException.h>

#include <iostream>

using namespace Inscoper;

const std::string SAMPLE_PATH = "instrument_sample.xml";

int main() {
    // Step 1: Import from a string
    // Importing replaces the whole content of the target object.
    NBO::Image image;

    image.fromXmlString(R"(<?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>)");

    std::cout << image.getID()->get() << " " << image.getName()->get() << std::endl;
    std::cout << image.getStageLabel_List().size() << std::endl;

    // Step 2: Import from a file
    NBO::Instrument instrument;
    instrument.fromXmlFile(SAMPLE_PATH);

    std::cout << instrument.getID()->get() << std::endl;
    for (const auto &objective : instrument.getObjective_List()) {
        std::cout << objective->getModel() << " " << objective->getMagnification() << std::endl;
    }

    // Step 3: Imported documents are validated
    // Values that violate the schema restrictions throw
    // InscoperNBOValidationException, which keeps invalid metadata out of the model.
    const std::string nonCompliant = R"(<?xml version="1.0"?>
<Image ID="NotAnImageIdentifier" />)";

    try {
        image.fromXmlString(nonCompliant);
    } catch (const NBO::InscoperNBOValidationException &error) {
        std::cout << "Rejected document: " << error.what() << std::endl;
    }

    // Pass false to import a non-compliant document as it is
    image.fromXmlString(nonCompliant, false);
    std::cout << image.getID()->get() << std::endl;

    return 0;
}
// --8<-- [end:main_logic]
