/*
 * Inscoper NBO Example: Export NBO-XML
 * ====================================
 * This example demonstrates how to serialize an NBO object tree to an XML string
 * or to an XML file, and how validation is applied on export.
 *
 * Prerequisites:
 * -------------
 * 1. Installation: inscoper-nbo-<version>.jar must be on the classpath.
 */

// --8<-- [start:main_logic]
import com.inscoper.nbo.BinData;
import com.inscoper.nbo.Denomination_Type;
import com.inscoper.nbo.Image;
import com.inscoper.nbo.ImageID_Type;
import com.inscoper.nbo.NonNegativeLong_Type;
import com.inscoper.nbo.StageLabel;

import java.nio.file.Path;
import java.nio.file.Paths;

public class ExportXml {
    public static void main(String[] args) {
        // Build a small tree: an image carrying three stage positions
        Image image = new Image();

        ImageID_Type imageId = new ImageID_Type();
        imageId.set("Image:1");
        image.setID(imageId);

        Denomination_Type name = new Denomination_Type();
        name.set("Field 1");
        image.setName(name);

        float[][] positions = {{0.0f, 0.0f}, {120.5f, 0.0f}, {241.0f, 0.0f}};
        for (int index = 0; index < positions.length; index++) {
            StageLabel stageLabel = new StageLabel();
            stageLabel.setName("Position " + index);
            stageLabel.setX(positions[index][0]);
            stageLabel.setY(positions[index][1]);
            image.addToStageLabel_List(stageLabel);
        }

        // Step 1: Serialize to a string
        System.out.println(image.toXmlString());

        // Step 2: Serialize to a file
        Path outputPath = Paths.get(System.getProperty("java.io.tmpdir"), "image.xml");
        image.toXmlFile(outputPath.toString());
        System.out.println("Written to " + outputPath);

        // Step 3: Control validation on export
        // Export validates the document by default: an element missing a required
        // attribute throws InscoperNBOValidationException, and attributes that carry a
        // schema default are written explicitly. Pass false to write exactly what was
        // set, at the cost of producing a document that may not be schema-valid.
        BinData binData = new BinData();
        binData.setBigEndian(true);
        NonNegativeLong_Type length = new NonNegativeLong_Type();
        length.set(12);
        binData.setLength(length);

        System.out.println(binData.toXmlString());        // validated: Compression="none"
        System.out.println(binData.toXmlString(false));   // as set: Compression is omitted
    }
}
// --8<-- [end:main_logic]
