/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.servicecomb.swagger.jakarta;

import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.type.TypeFactory;

import io.swagger.converter.ModelConverter;
import io.swagger.converter.ModelConverterContextImpl;
import io.swagger.models.Model;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * replace io.swagger.converter.ModelConverters to adapter JAVAEE9 jakarta API
 * modifying content: converters add ModelResolverAdapterJakarta to adapter jakarta.
 */
public class ModelConvertersAdapterJakarta {
  private static final ModelConvertersAdapterJakarta SINGLETON = new ModelConvertersAdapterJakarta();
  static Logger LOGGER = LoggerFactory.getLogger(io.swagger.converter.ModelConverters.class);
  private final List<ModelConverter> converters;
  private final Set<String> skippedPackages = new HashSet<String>();
  private final Set<String> skippedClasses = new HashSet<String>();

  public ModelConvertersAdapterJakarta() {
    converters = new CopyOnWriteArrayList<ModelConverter>();
    converters.add(new ModelResolverAdapterJakarta(Json.mapper()));
  }

  public static ModelConvertersAdapterJakarta getInstance() {
    return SINGLETON;
  }

  public void addConverter(ModelConverter converter) {
    converters.add(0, converter);
  }

  public void removeConverter(ModelConverter converter) {
    converters.remove(converter);
  }

  public void addPackageToSkip(String pkg) {
    this.skippedPackages.add(pkg);
  }

  public void addClassToSkip(String cls) {
    LOGGER.warn("skipping class " + cls);
    this.skippedClasses.add(cls);
  }

  public Property readAsProperty(Type type) {
    return readAsProperty(type, null);
  }

  public Property readAsProperty(Type type, JsonView jsonView) {
    ModelConverterContextImpl context = new ModelConverterContextImpl(converters);
    context.setJsonView(jsonView);
    return context.resolveProperty(type, null);
  }

  public Map<String, Model> read(Type type) {
    return read(type, null);
  }

  public Map<String, Model> read(Type type, JsonView jsonView) {
    Map<String, Model> modelMap = new HashMap<String, Model>();
    if (shouldProcess(type)) {
      ModelConverterContextImpl context = new ModelConverterContextImpl(
          converters);
      context.setJsonView(jsonView);
      Model resolve = context.resolve(type);
      for (Entry<String, Model> entry : context.getDefinedModels()
          .entrySet()) {
        if (entry.getValue().equals(resolve)) {
          modelMap.put(entry.getKey(), entry.getValue());
        }
      }
    }
    return modelMap;
  }

  public Map<String, Model> readAll(Type type) {
    return readAll(type, null);
  }

  public Map<String, Model> readAll(Type type, JsonView annotation) {
    if (shouldProcess(type)) {
      ModelConverterContextImpl context = new ModelConverterContextImpl(
          converters);
      context.setJsonView(annotation);

      LOGGER.debug("ModelConvertersAdapterJakarta readAll with JsonView annotation from " + type);
      context.resolve(type);
      return context.getDefinedModels();
    }
    return new HashMap<String, Model>();
  }

  private boolean shouldProcess(Type type) {
    final Class<?> cls = TypeFactory.defaultInstance().constructType(type).getRawClass();
    if (cls.isPrimitive()) {
      return false;
    }
    String className = cls.getName();
    for (String packageName : skippedPackages) {
      if (className.startsWith(packageName)) {
        return false;
      }
    }
    for (String classToSkip : skippedClasses) {
      if (className.equals(classToSkip)) {
        return false;
      }
    }
    return true;
  }

  static {
    SINGLETON.skippedPackages.add("java.lang");

    ServiceLoader<ModelConverter> loader = ServiceLoader.load(ModelConverter.class);
    Iterator<ModelConverter> itr = loader.iterator();
    while (itr.hasNext()) {
      ModelConverter ext = itr.next();
      if (ext == null) {
        LOGGER.error("failed to load extension " + ext);
      } else {
        SINGLETON.addConverter(ext);
        LOGGER.debug("adding ModelConverter: " + ext);
      }
    }
  }
}
