/*
 * This file is part of ***  M y C o R e  ***
 * See http://www.mycore.de/ for details.
 *
 * MyCoRe is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MyCoRe is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.mycore.user2.utils;

import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.MCRException;
import org.mycore.common.content.MCRJAXBContent;
import org.mycore.user2.MCRRole;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;

/**
 * @author Thomas Scheffler (yagee)
 *
 */
public abstract class MCRRoleTransformer {

    private static final String ROLE_ELEMENT_NAME = "role";

    private static final JAXBContext JAXB_CONTEXT = initContext();

    private static JAXBContext initContext() {
        try {
            return JAXBContext.newInstance(MCRRole.class.getPackage().getName(), MCRRole.class.getClassLoader());
        } catch (JAXBException e) {
            throw new MCRException("Could not instantiate JAXBContext.", e);
        }
    }

    /**
     * Builds an xml element containing all information on the given role.
     */
    public static Document buildExportableXML(MCRRole role) {
        MCRJAXBContent<MCRRole> content = new MCRJAXBContent<>(JAXB_CONTEXT, role);
        try {
            return content.asXML();
        } catch (IOException e) {
            throw new MCRException("Exception while transforming MCRRole " + role.getName() + " to JDOM document.", e);
        }
    }

    /**
     * Builds an MCRRole instance from the given element.
     * @param element as generated by {@link #buildExportableXML(MCRRole)}. 
     */
    public static MCRRole buildMCRRole(Element element) {
        if (!element.getName().equals(ROLE_ELEMENT_NAME)) {
            throw new IllegalArgumentException("Element is not a mycore role element.");
        }
        try {
            Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            return (MCRRole) unmarshaller.unmarshal(new JDOMSource(element));
        } catch (JAXBException e) {
            throw new MCRException("Exception while transforming Element to MCRUser.", e);
        }
    }

}
