/*-
 * ~~~~~~licensing~~~~~~
 * core-support-runtime
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.support.runtime.cxf;

import java.lang.reflect.Proxy;

import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.common.util.ClassUnwrapper;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.common.util.SystemPropertyAction;

/**
 * Nearly exact copy of org.apache.cxf.common.util.ClassHelper
 * We need to provide default behavior in custom class unwrapper 
 * similar to default CXF behavior,
 * but don't have access to CXF protected classes, methods and fields
 *  
 */
public class EntaxyCxfClassHelper {


    public static final String USE_DEFAULT_CLASS_HELPER = "org.apache.cxf.useDefaultClassHelpers";

    static final EntaxyCxfClassHelper HELPER;
    static final ClassUnwrapper DEFAULT_UNWRAPPER;
    static final ClassUnwrapper UNWRAPPER;
    
    /**
     * Default class unwrapper implementation which delegates to the ClassHelper
     * internal methods.
     *
     */
    private static class DefaultClassUnwrapper implements ClassUnwrapper {
        private final EntaxyCxfClassHelper helper;
        
        DefaultClassUnwrapper(EntaxyCxfClassHelper helper) {
            this.helper = helper;
        }
        
        @Override
        public Class<?> getRealClassFromClass(Class<?> clazz) {
            return helper.getRealClassFromClassInternal(clazz);
        }
        
        @Override
        public Class<?> getRealClass(Object o) {
            return helper.getRealClassInternal(o);
        }
        
        @Override
        public Object getRealObject(Object o) {
            return helper.getRealObjectInternal(o);
        }
    }

    static {
        HELPER = new EntaxyCxfClassHelper();
        DEFAULT_UNWRAPPER = new DefaultClassUnwrapper(HELPER);
        UNWRAPPER = getClassUnwrapper(DEFAULT_UNWRAPPER);
    }

    protected EntaxyCxfClassHelper() {
    }

    private static ClassUnwrapper getClassUnwrapper(ClassUnwrapper defaultHelper) {
        boolean useSpring = true;
        String s = SystemPropertyAction.getPropertyOrNull("org.apache.cxf.useSpringClassHelpers");
        if (!StringUtils.isEmpty(s)) {
            useSpring = "1".equals(s) || Boolean.parseBoolean(s);
        }
        if (useSpring) {
            try {
                return new EntaxyCxfSpringClassUnwrapper();
            } catch (Throwable ex) {
                // ignore
            }
        }
        return defaultHelper;
    }

    private Class<?> getRealClassInternal(Object o) {
        return getRealObjectInternal(o).getClass();
    }

    private Class<?> getRealClassFromClassInternal(Class<?> cls) {
        return cls;
    }

    private Object getRealObjectInternal(Object o) {
        return o instanceof Proxy ? Proxy.getInvocationHandler(o) : o;
    }

    public static Class<?> getRealClass(Object o) {
        return getRealClass(null, o);
    }

    public static Class<?> getRealClassFromClass(Class<?> cls) {
        return getRealClassFromClass(null, cls);
    }

    public static Class<?> getRealClassFromClass(Bus bus, Class<?> cls) {
        return getContextClassUnwrapper(getBus(bus)).getRealClassFromClass(cls);
    }

    public static Object getRealObject(Object o) {
        return getContextClassUnwrapper(getBus(null)).getRealObject(o);
    }

    public static Class<?> getRealClass(Bus bus, Object o) {
        return getContextClassUnwrapper(getBus(bus)).getRealClass(o);
    }

    private static ClassUnwrapper getContextClassUnwrapper(Bus bus) {
        if (bus != null && bus.getProperty(ClassUnwrapper.class.getName()) != null) {
            ClassUnwrapper unwrapper = (ClassUnwrapper) bus.getProperty(ClassUnwrapper.class.getName());
            return unwrapper;
        }

        return (DEFAULT_UNWRAPPER == UNWRAPPER || checkUseDefaultClassHelper(bus)) ? DEFAULT_UNWRAPPER : UNWRAPPER;
    }

    private static Bus getBus(Bus bus) {
        return bus == null ? BusFactory.getThreadDefaultBus() : bus;
    }

    private static boolean checkUseDefaultClassHelper(Bus bus) {
        return bus != null && Boolean.TRUE.equals(bus.getProperty(USE_DEFAULT_CLASS_HELPER));
    }

    public static ClassUnwrapper getDefaultClassUnwrapper(Bus bus) {
    	return (DEFAULT_UNWRAPPER == UNWRAPPER || checkUseDefaultClassHelper(bus)) ? DEFAULT_UNWRAPPER : UNWRAPPER;
    }
}
