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

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.MCRUser;

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

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

    private static final String USER_ELEMENT_NAME = "user";

    public static final JAXBContext JAXB_CONTEXT = initContext();

    private MCRUserTransformer() {
    }

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

    private static Document getDocument(MCRUser user) {
        MCRJAXBContent<MCRUser> content = new MCRJAXBContent<>(JAXB_CONTEXT, user);
        try {
            Document userXML = content.asXML();
            sortAttributes(userXML);
            return userXML;
        } catch (IOException e) {
            throw new MCRException("Exception while transforming MCRUser " + user.getUserID() + " to JDOM document.",
                e);
        }
    }

    private static void sortAttributes(Document userXML) {
        Element attributes = userXML.getRootElement().getChild("attributes");
        if (attributes == null) {
            return;
        }
        attributes.sortChildren(Comparator.comparing(o -> o.getAttributeValue("name")));
    }

    /**
     * Builds an xml element containing basic information on user. 
     * This includes user ID, login name and realm.
     */
    public static Document buildBasicXML(MCRUser mcrUser) {
        return getDocument(mcrUser.getBasicCopy());
    }

    /**
     * Builds an xml element containing all information on the given user except password info.
     * same as {@link #buildExportableXML(MCRUser)} without owned users resolved
     */
    public static Document buildExportableSafeXML(MCRUser mcrUser) {
        return getDocument(mcrUser.getSafeCopy());
    }

    /**
     * Builds an xml element containing all information on the given user.
     * same as {@link #buildExportableSafeXML(MCRUser)} but with password info if available
     */
    public static Document buildExportableXML(MCRUser mcrUser) {
        return getDocument(mcrUser);
    }

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

}
