/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package leigh.eo.schema.dao;

import leigh.eo.EO;
import leigh.eo.EOLoop;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.util.UUID;

/**
 * Previously the schema contained a pointer to the root element. In the modern incarnation the root element
 * always has the same API name as the schema itself, and therefore can always be inferred. This came about because there
 * was seldom/never a practical situation where they needed to be different.
 *
 * @author Alex Leigh
 */
public final class SchemaUtil {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(SchemaUtil.class);
    public static String API_KEY = SchemaElementDAO.API_TYPE;
    public static String KEY_ELEMENTS = "elements";
    public static String KEY_API_NAME = "apiName";
    // The magical schema ID. This is a global constant.
    public static UUID SCHEMA_ID = UUID.fromString("0684fb60-16a9-11e4-8c21-0800200c9a66");

    public static EO createLabelField(String fieldName, String fieldDesc) {
        return LoopUtil.create(fieldName, fieldDesc, new String[]{TextElementDAO.API_TYPE});
    }

    public static EO createLabelField() {
        return createLabelField("label", "Label");
    }

    @Deprecated
    public static EO create() {
        final EO eo = new EO(API_KEY);
        eo.setValue(KEY_ELEMENTS, new EOLoop());
        return eo;
    }

    public static EO getRootElement(final EO schema) {
        logger.debug("Searching for root element in: {}", schema);
        return getElement(schema, SchemaElementDAO.getApiName(schema));
    }

    public static EO getElement(final EO schema, final String apiName) {
        for (final EO element : SchemaElementDAO.getElements(schema)) {
            if (ElementElementDAO.getApiName(element).equals(apiName))
                return element;
        }
        return null;
    }

    public static EO create(final String apiName) {
        final EO eo = SchemaElementDAO.create();
        SchemaElementDAO.setApiName(eo, apiName);
        return eo;
    }


    public static void addElement(final EO eo, final EO element) {
        EOLoop loop = (EOLoop) eo.getValue(KEY_ELEMENTS);
        if (loop == null) {
            loop = new EOLoop();
            eo.setValue(KEY_ELEMENTS, loop);
        }
        loop.add(element);
    }
}