/* OdLib_Elements - Copyright (c) 2008-2021 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.opendocument.elements;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 *
 * @author Vincent Calame
 */
public abstract class OdElement implements Constants {

    @SuppressWarnings({"unchecked"})
    private final Map<OdAttribute, String>[] attributeMapArray = new Map[ATTRIBUTES_LENGTH];

    public OdElement() {
    }

    private Map<OdAttribute, String> getOrCreateAttributeMap(int attributeType) {
        Map<OdAttribute, String> map = attributeMapArray[attributeType - 1];
        if (map == null) {
            map = new HashMap<OdAttribute, String>();
            attributeMapArray[attributeType - 1] = map;
        }
        return map;
    }

    public void importAttributes(OdElement importElement) {
        for (int i = 0; i < ATTRIBUTES_LENGTH; i++) {
            Map<OdAttribute, String> map = importElement.attributeMapArray[i];
            if (map == null) {
                continue;
            }
            Map<OdAttribute, String> destinationMap = attributeMapArray[i];
            if (destinationMap == null) {
                destinationMap = new HashMap<OdAttribute, String>(map);
                attributeMapArray[i] = destinationMap;
            } else {
                for (Map.Entry<OdAttribute, String> entry : map.entrySet()) {
                    OdAttribute key = entry.getKey();
                    if (!destinationMap.containsKey(entry.getKey())) {
                        destinationMap.put(key, entry.getValue());
                    }
                }
            }
        }
    }

    public OdElement putAttribute(String name, String value) {
        int[] avalaibleTypeArray = getAvalaibleTypeArray();
        OdAttribute attribute = OdAttributeMap.getAttribute(avalaibleTypeArray, name);
        if (attribute == null) {
            return this;
        }
        Map<OdAttribute, String> map = getOrCreateAttributeMap(attribute.getAttributeType());
        if (OdElementUtils.isStyleNameAttribute(name)) {
            value = OdElementUtils.checkStyleNameValue(value);
        }
        map.put(attribute, value);
        return this;
    }

    public Map<OdAttribute, String> getAttributeMap(int attributeType) {
        Map<OdAttribute, String> map = attributeMapArray[attributeType - 1];
        if (map == null) {
            return Collections.emptyMap();
        }
        return map;
    }

    public abstract int[] getAvalaibleTypeArray();


}
