/*-
 * ~~~~~~licensing~~~~~~
 * atlasmap-entaxy-services
 * ==========
 * 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~~~~~~
 */
/*
 * Copyright (C) 2017 Red Hat, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package io.atlasmap.v2;

import java.io.IOException;
import java.util.HashMap;
import java.util.ServiceLoader;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
import com.fasterxml.jackson.databind.type.TypeFactory;

import io.atlasmap.spi.entaxy.EntaxyAction;

public class SimpleResolver extends TypeIdResolverBase {

    protected final HashMap<Class<?>, String> typeToId = new HashMap<Class<?>, String>();
    protected final HashMap<String, JavaType> idToType = new HashMap<String, JavaType>();

    private JavaType baseType;
    private ClassLoader classLoader;
    private TypeFactory typeFactory;

    @Override
    public void init(JavaType baseType) {
        this.baseType = baseType;
        Class<?> baseClass = baseType.getRawClass();

        ServiceLoader<?> implementations =
                ServiceLoader.load(baseClass, this.classLoader != null ? this.classLoader : baseClass.getClassLoader());
        for (Object o : implementations) {
            Class<?> c = o.getClass();
            if (c != baseClass && baseClass.isAssignableFrom(c)) {
                JsonTypeName jsonAnnoation = c.getAnnotation(JsonTypeName.class);

                // Use short ids for classes in the same package..
                String id = null;
                if (c.getPackage().getName().equals(baseClass.getPackage().getName())) {
                    if (jsonAnnoation != null && jsonAnnoation.value() != null) {
                        id = jsonAnnoation.value();
                    } else {
                        id = c.getSimpleName();
                    }
                } else {
                    // check Entaxy-specific annotation
                    if (c.isAnnotationPresent(EntaxyAction.class)) {
                        id = c.getAnnotation(EntaxyAction.class).actionId();
                    } else {
                        // All other extensions need fully qualified names.
                        id = c.getName();
                    }
                }
                typeToId.put(c, id);
                idToType.put(id, typeFactory.constructSpecializedType(baseType, c));
            }
        }
    }

    @Override
    public JsonTypeInfo.Id getMechanism() {
        return JsonTypeInfo.Id.CUSTOM;
    }

    @Override
    public String idFromValue(Object value) {
        return idFromValueAndType(value, value.getClass());
    }

    @Override
    public String idFromValueAndType(Object value, Class<?> aClass) {
        String rc = typeToId.get(aClass);
        if (rc == null) {
            throw new IllegalArgumentException("Invalid type: " + aClass);
        }
        return rc;
    }

    @Override
    public String idFromBaseType() {
        return idFromValueAndType(null, baseType.getRawClass());
    }

    @Override
    public JavaType typeFromId(DatabindContext databindContext, String id) throws IOException {
        JavaType rc = idToType.get(id);
        if (rc == null) {
            throw new IllegalArgumentException("Invalid type id: " + id);
        }
        return rc;
    }

    @Override
    public String getDescForKnownTypeIds() {
        return "valid values: " + idToType.keySet();
    }

    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    public ClassLoader getClassLoader() {
        return this.classLoader;
    }

    public void setTypeFactory(TypeFactory tf) {
        this.typeFactory = tf;
    }
}
