////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////

package pp.battleship.exporter;

import com.jme3.app.SimpleApplication;
import com.jme3.export.JmeExporter;
import com.jme3.export.binary.BinaryExporter;
import com.jme3.scene.Spatial;
import com.jme3.system.JmeContext;
import com.jme3.util.TangentBinormalGenerator;

import java.io.File;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;

/**
 * This class transforms models into j3o format.
 */
public class ModelExporter extends SimpleApplication {
    private static final Logger LOGGER = System.getLogger(ModelExporter.class.getName());

    /**
     * The main method of the converter
     *
     * @param args input args
     */
    public static void main(String[] args) {
        ModelExporter application = new ModelExporter();
        application.start(JmeContext.Type.Headless);
    }

    /**
     * Overrides  {@link com.jme3.app.SimpleApplication#simpleInitApp()}.
     * It initializes a simple app by exporting robots and rocks.
     */
    @Override
    public void simpleInitApp() {
        export("Models/KingGeorgeV/King_George_V.obj", "KingGeorgeV.j3o"); //NON-NLS

        stop();
    }

    /**
     * Exports spatial into a file
     *
     * @param fileName       the file name of the model
     * @param exportFileName the name of the file where the .j3o file is going to be stored
     */
    private void export(String fileName, String exportFileName) {
        final File file = new File(exportFileName);
        JmeExporter exporter = BinaryExporter.getInstance();
        try {
            final Spatial model = getAssetManager().loadModel(fileName);
            TangentBinormalGenerator.generate(model);
            exporter.save(model, file);
        }
        catch (IOException exception) {
            LOGGER.log(Level.ERROR, "write to {0} failed", file); //NON-NLS
            throw new RuntimeException(exception);
        }
        LOGGER.log(Level.INFO, "wrote file {0}", file); //NON-NLS
    }
}
