/*
 * 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 java.util.Locale;

/**
 * Utility class for interacting with Text elements.
 *
 * @author Alex Leigh
 */
public class TextUtil {
    public static final Locale defaultLocale = Locale.ENGLISH;

    public static String getDefaultText(EOLoop loop) {
        return getText(loop, defaultLocale);
    }


    public static EO defaultLabel(final String text) {
        final EO label = TextElementDAO.create();
        TextElementDAO.setText(label, text);
        TextElementDAO.setLocale(label, defaultLocale);
        return label;
    }

    /**
     * Given a loop of <code>TextElement</code> EOs, return the one that matches the given locale.
     *
     * @param loop
     * @return
     */
    public static String getText(EOLoop loop, Locale locale) {
        for (EO text : loop) {
            if (!TextElementDAO.assertType(text))
                continue;
            if (locale.equals(TextElementDAO.getLocale(text)))
                return TextElementDAO.getText(text);
        }

        for (EO text : loop) {
            if (!TextElementDAO.assertType(text))
                continue;
            if (defaultLocale.equals(TextElementDAO.getLocale(text)))
                return TextElementDAO.getText(text);
        }

        return null;
    }

    public static Locale getDefaultLocale() {
        return defaultLocale;
    }

    public static String getLabelValueString(EO src, String key, Locale locale) {
        EOLoop loop = src.getValueLoop(key);
        if (loop != null) {
            return getText(loop, locale);
        }
        return null;
    }
}