/**
 *                                  Apache License
 *                            Version 2.0, January 2004
 *                         http://www.apache.org/licenses/
 *
 *    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 *
 *    1. Definitions.
 *
 *       "License" shall mean the terms and conditions for use, reproduction,
 *       and distribution as defined by Sections 1 through 9 of this document.
 *
 *       "Licensor" shall mean the copyright owner or entity authorized by
 *       the copyright owner that is granting the License.
 *
 *       "Legal Entity" shall mean the union of the acting entity and all
 *       other entities that control, are controlled by, or are under common
 *       control with that entity. For the purposes of this definition,
 *       "control" means (i) the power, direct or indirect, to cause the
 *       direction or management of such entity, whether by contract or
 *       otherwise, or (ii) ownership of fifty percent (50%) or more of the
 *       outstanding shares, or (iii) beneficial ownership of such entity.
 *
 *       "You" (or "Your") shall mean an individual or Legal Entity
 *       exercising permissions granted by this License.
 *
 *       "Source" form shall mean the preferred form for making modifications,
 *       including but not limited to software source code, documentation
 *       source, and configuration files.
 *
 *       "Object" form shall mean any form resulting from mechanical
 *       transformation or translation of a Source form, including but
 *       not limited to compiled object code, generated documentation,
 *       and conversions to other media types.
 *
 *       "Work" shall mean the work of authorship, whether in Source or
 *       Object form, made available under the License, as indicated by a
 *       copyright notice that is included in or attached to the work
 *       (an example is provided in the Appendix below).
 *
 *       "Derivative Works" shall mean any work, whether in Source or Object
 *       form, that is based on (or derived from) the Work and for which the
 *       editorial revisions, annotations, elaborations, or other modifications
 *       represent, as a whole, an original work of authorship. For the purposes
 *       of this License, Derivative Works shall not include works that remain
 *       separable from, or merely link (or bind by name) to the interfaces of,
 *       the Work and Derivative Works thereof.
 *
 *       "Contribution" shall mean any work of authorship, including
 *       the original version of the Work and any modifications or additions
 *       to that Work or Derivative Works thereof, that is intentionally
 *       submitted to Licensor for inclusion in the Work by the copyright owner
 *       or by an individual or Legal Entity authorized to submit on behalf of
 *       the copyright owner. For the purposes of this definition, "submitted"
 *       means any form of electronic, verbal, or written communication sent
 *       to the Licensor or its representatives, including but not limited to
 *       communication on electronic mailing lists, source code control systems,
 *       and issue tracking systems that are managed by, or on behalf of, the
 *       Licensor for the purpose of discussing and improving the Work, but
 *       excluding communication that is conspicuously marked or otherwise
 *       designated in writing by the copyright owner as "Not a Contribution."
 *
 *       "Contributor" shall mean Licensor and any individual or Legal Entity
 *       on behalf of whom a Contribution has been received by Licensor and
 *       subsequently incorporated within the Work.
 *
 *    2. Grant of Copyright License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       copyright license to reproduce, prepare Derivative Works of,
 *       publicly display, publicly perform, sublicense, and distribute the
 *       Work and such Derivative Works in Source or Object form.
 *
 *    3. Grant of Patent License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       (except as stated in this section) patent license to make, have made,
 *       use, offer to sell, sell, import, and otherwise transfer the Work,
 *       where such license applies only to those patent claims licensable
 *       by such Contributor that are necessarily infringed by their
 *       Contribution(s) alone or by combination of their Contribution(s)
 *       with the Work to which such Contribution(s) was submitted. If You
 *       institute patent litigation against any entity (including a
 *       cross-claim or counterclaim in a lawsuit) alleging that the Work
 *       or a Contribution incorporated within the Work constitutes direct
 *       or contributory patent infringement, then any patent licenses
 *       granted to You under this License for that Work shall terminate
 *       as of the date such litigation is filed.
 *
 *    4. Redistribution. You may reproduce and distribute copies of the
 *       Work or Derivative Works thereof in any medium, with or without
 *       modifications, and in Source or Object form, provided that You
 *       meet the following conditions:
 *
 *       (a) You must give any other recipients of the Work or
 *           Derivative Works a copy of this License; and
 *
 *       (b) You must cause any modified files to carry prominent notices
 *           stating that You changed the files; and
 *
 *       (c) You must retain, in the Source form of any Derivative Works
 *           that You distribute, all copyright, patent, trademark, and
 *           attribution notices from the Source form of the Work,
 *           excluding those notices that do not pertain to any part of
 *           the Derivative Works; and
 *
 *       (d) If the Work includes a "NOTICE" text file as part of its
 *           distribution, then any Derivative Works that You distribute must
 *           include a readable copy of the attribution notices contained
 *           within such NOTICE file, excluding those notices that do not
 *           pertain to any part of the Derivative Works, in at least one
 *           of the following places: within a NOTICE text file distributed
 *           as part of the Derivative Works; within the Source form or
 *           documentation, if provided along with the Derivative Works; or,
 *           within a display generated by the Derivative Works, if and
 *           wherever such third-party notices normally appear. The contents
 *           of the NOTICE file are for informational purposes only and
 *           do not modify the License. You may add Your own attribution
 *           notices within Derivative Works that You distribute, alongside
 *           or as an addendum to the NOTICE text from the Work, provided
 *           that such additional attribution notices cannot be construed
 *           as modifying the License.
 *
 *       You may add Your own copyright statement to Your modifications and
 *       may provide additional or different license terms and conditions
 *       for use, reproduction, or distribution of Your modifications, or
 *       for any such Derivative Works as a whole, provided Your use,
 *       reproduction, and distribution of the Work otherwise complies with
 *       the conditions stated in this License.
 *
 *    5. Submission of Contributions. Unless You explicitly state otherwise,
 *       any Contribution intentionally submitted for inclusion in the Work
 *       by You to the Licensor shall be under the terms and conditions of
 *       this License, without any additional terms or conditions.
 *       Notwithstanding the above, nothing herein shall supersede or modify
 *       the terms of any separate license agreement you may have executed
 *       with Licensor regarding such Contributions.
 *
 *    6. Trademarks. This License does not grant permission to use the trade
 *       names, trademarks, service marks, or product names of the Licensor,
 *       except as required for reasonable and customary use in describing the
 *       origin of the Work and reproducing the content of the NOTICE file.
 *
 *    7. Disclaimer of Warranty. Unless required by applicable law or
 *       agreed to in writing, Licensor provides the Work (and each
 *       Contributor provides its Contributions) on an "AS IS" BASIS,
 *       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 *       implied, including, without limitation, any warranties or conditions
 *       of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
 *       PARTICULAR PURPOSE. You are solely responsible for determining the
 *       appropriateness of using or redistributing the Work and assume any
 *       risks associated with Your exercise of permissions under this License.
 *
 *    8. Limitation of Liability. In no event and under no legal theory,
 *       whether in tort (including negligence), contract, or otherwise,
 *       unless required by applicable law (such as deliberate and grossly
 *       negligent acts) or agreed to in writing, shall any Contributor be
 *       liable to You for damages, including any direct, indirect, special,
 *       incidental, or consequential damages of any character arising as a
 *       result of this License or out of the use or inability to use the
 *       Work (including but not limited to damages for loss of goodwill,
 *       work stoppage, computer failure or malfunction, or any and all
 *       other commercial damages or losses), even if such Contributor
 *       has been advised of the possibility of such damages.
 *
 *    9. Accepting Warranty or Additional Liability. While redistributing
 *       the Work or Derivative Works thereof, You may choose to offer,
 *       and charge a fee for, acceptance of support, warranty, indemnity,
 *       or other liability obligations and/or rights consistent with this
 *       License. However, in accepting such obligations, You may act only
 *       on Your own behalf and on Your sole responsibility, not on behalf
 *       of any other Contributor, and only if You agree to indemnify,
 *       defend, and hold each Contributor harmless for any liability
 *       incurred by, or claims asserted against, such Contributor by reason
 *       of your accepting any such warranty or additional liability.
 *
 *    END OF TERMS AND CONDITIONS
 *
 *    APPENDIX: How to apply the Apache License to your work.
 *
 *       To apply the Apache License to your work, attach the following
 *       boilerplate notice, with the fields enclosed by brackets "{}"
 *       replaced with your own identifying information. (Don't include
 *       the brackets!)  The text should be enclosed in the appropriate
 *       comment syntax for the file format. We also recommend that a
 *       file or class name and description of purpose be included on the
 *       same "printed page" as the copyright notice for easier
 *       identification within third-party archives.
 *
 *    Copyright 2014 Edgar Espina
 *
 *    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 org.jooby.apitool.raml;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.inject.internal.MoreTypes;
import io.swagger.converter.ModelConverters;
import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.PropertyBuilder;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty;
import org.jooby.MediaType;
import org.jooby.apitool.RouteMethod;
import org.jooby.apitool.RouteParameter;
import org.jooby.apitool.RouteResponse;
import org.jooby.internal.apitool.FriendlyTypeName;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * RAML objects for describing a RAML definition file. This is a partial representation of the RAML
 * specification.
 *
 * @since 1.2.0
 * @author edgar
 */
public class Raml {
  private String title;

  private String version;

  private String baseUri;

  private List<String> mediaType;

  private List<String> protocols;

  private Map<String, RamlType> types;

  private Map<String, RamlPath> resources = new LinkedHashMap<>();

  /**
   * RAML title.
   *
   * @return RAML title.
   */
  public String getTitle() {
    return title;
  }

  /**
   * Set RAML title.
   *
   * @param title RAML title.
   */
  public void setTitle(final String title) {
    this.title = title;
  }

  /**
   * RAML version.
   *
   * @return RAML version.
   */
  public String getVersion() {
    return version;
  }

  /**
   * Set RAML version.
   *
   * @param version RAML version.
   */
  public void setVersion(final String version) {
    this.version = version;
  }

  /**
   * RAML base uri.
   *
   * @return RAML base uri.
   */
  public String getBaseUri() {
    return baseUri;
  }

  /**
   * Set base uri.
   *
   * @param baseUri Base uri.
   */
  public void setBaseUri(final String baseUri) {
    this.baseUri = baseUri;
  }

  /**
   * Get media types.
   *
   * @return Media types.
   */
  public List<String> getMediaType() {
    return mediaType;
  }

  /**
   * Set media types.
   *
   * @param mediaType Media types.
   */
  public void setMediaType(final List<String> mediaType) {
    this.mediaType = mediaType;
  }

  /**
   * Get protocols.
   *
   * @return Protocols.
   */
  public List<String> getProtocols() {
    return protocols;
  }

  /**
   * Set protocols.
   *
   * @param protocols Protocols.
   */
  public void setProtocols(final List<String> protocols) {
    this.protocols = protocols;
  }

  /**
   * RAML types.
   *
   * @return RAML types.
   */
  public Map<String, RamlType> getTypes() {
    return types;
  }

  /**
   * Get resources.
   *
   * @return Resources.
   */
  @JsonAnyGetter
  public Map<String, RamlPath> getResources() {
    return resources;
  }

  /**
   * Get a path for the given pattern. If the path doesn't exist, a new path will be created.
   *
   * @param pattern Pattern.
   * @return Path for the given pattern.
   */
  public RamlPath path(String pattern) {
    RamlPath path = resources.get(pattern);
    if (path == null) {
      path = new RamlPath();
      resources.put(pattern, path);
    }
    return path;
  }

  /**
   * Define/map a custom Java type to RAML type.
   *
   * <pre>
   *   RamlType uuid = raml.define(UUID.class, RamlType.STRING);
   *   uuid.setPattern("...");
   * </pre>
   *
   * @param javaType Java type.
   * @param baseType RAML base type.
   * @return New RAML type.
   */
  public RamlType define(Type javaType, RamlType baseType) {
    Objects.requireNonNull(javaType, "Java type required.");
    Objects.requireNonNull(baseType, "Raml type required.");
    if (types == null) {
      types = new LinkedHashMap<>();
    }
    String typeName = MoreTypes.getRawType(javaType).getSimpleName();
    RamlType ramlType = new RamlType(baseType.getType(), typeName);
    types.put(typeName, ramlType);
    return ramlType;
  }

  /**
   * Register a Java type and produces an equivalent RAML type. It returns an existing RAML type if
   * the Java type was registered already.
   *
   * @param type Java type.
   * @return RAML type.
   */
  public RamlType define(Type type) {
    if (types == null) {
      types = new LinkedHashMap<>();
    }
    Type componentType = componentType(type);
    String typeName = MoreTypes.getRawType(componentType).getSimpleName();
    RamlType ramlType = RamlType.valueOf(typeName);
    if (ramlType.isObject()) {
      RamlType existing = types.get(typeName);
      if (existing == null) {
        ModelConverters converter = ModelConverters.getInstance();
        Property property = converter.readAsProperty(componentType);

        Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<>(
            PropertyBuilder.PropertyId.class);
        for (Map.Entry<String, Model> entry : converter.readAll(componentType).entrySet()) {
          define(entry.getKey(), entry.getValue());
        }
        ramlType = define(typeName, PropertyBuilder.toModel(PropertyBuilder.merge(property, args)));
      } else {
        ramlType = existing;
      }
    }

    return type != componentType ? ramlType.toArray() : ramlType;
  }

  private Type componentType(final Type type) {
    Class<?> rawType = MoreTypes.getRawType(type);
    if (rawType.isArray()) {
      return rawType.getComponentType();
    }
    if (Collection.class.isAssignableFrom(rawType) && type instanceof ParameterizedType) {
      return ((ParameterizedType) type).getActualTypeArguments()[0];
    }
    return type;
  }

  private RamlType define(final String type, final Model model) {
    RamlType definition = types.get(type);
    if (definition == null) {
      RamlType object = new RamlType("object", type);
      types.put(type, object);
      Map<String, Object> example = new LinkedHashMap<>();
      Optional.ofNullable(model.getProperties())
          .ifPresent(properties -> properties.forEach((name, property) -> {
            if (property instanceof RefProperty) {
              String propertyType = propertyType(property);
              object.newProperty(name, propertyType, false);
            } else if (property instanceof ArrayProperty) {
              String propertyType = propertyType(((ArrayProperty) property).getItems()) + "[]";
              object.newProperty(name, propertyType, false);
            } else {
              String propertyType = propertyType(property);
              List<String> enums = null;
              if (property instanceof StringProperty) {
                enums = ((StringProperty) property).getEnum();
              }
              RamlType ramlType = RamlType.valueOf(propertyType);
              // String propertyType = ramlType.isObject() ? property.getType() : ramlType.getType();
              object.newProperty(name, propertyType, false,
                  Optional.ofNullable(enums).map(it -> it.toArray(new String[it.size()]))
                      .orElse(new String[0]));
              example.put(name, Optional.ofNullable(enums).<Object>map(it -> it.get(0))
                  .orElse(ramlType.getExample()));
            }
          }));
      definition = object;
      if (example.values().stream().filter(Objects::nonNull).count() > 0) {
        object.setExample(example);
      }
    }
    return definition;
  }

  private String propertyType(Property property) {
    if (property instanceof RefProperty) {
      return ((RefProperty) property).getSimpleRef();
    }
    // Special handling for uuid type reported by Swagger converter
    String type = property.getType();
    if (property instanceof UUIDProperty) {
      type = UUID.class.getSimpleName();
    }
    RamlType ramlType = types.get(type);
    return ramlType == null ? property.getType() : ramlType.getRef().getType();
  }

  /**
   * Set RAML paths.
   *
   * @param resources RAML paths.
   */
  public void setResources(final Map<String, RamlPath> resources) {
    this.resources = resources;
  }

  /**
   * Convert this RAML object to Yaml.
   *
   * @return Yaml string.
   * @throws IOException If something goes wrong.
   */
  public String toYaml() throws IOException {
    YAMLMapper mapper = new YAMLMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, false);
    mapper.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true);
    return "#%RAML 1.0\n" + mapper.writer().withDefaultPrettyPrinter().writeValueAsString(this);
  }

  /**
   * Build a {@link Raml} object from list of {@link RouteMethod}.
   *
   * @param base Base raml (might be null).
   * @param routes List of routes.
   * @return RAML object.
   */
  public static Raml build(Raml base, List<RouteMethod> routes) {
    Raml raml = Optional.ofNullable(base).orElseGet(Raml::new);
    BiFunction<RamlPath, String, RamlPath> pathFactory = (path, segment) ->
        path == null ? raml.path(segment) : path.path(segment);

    BiConsumer<Function<String, RamlParameter>, RouteParameter> parameterFactory = (factory, parameter) -> {
      RamlParameter p = factory.apply(parameter.name());
      p.setDescription(parameter.description()
          .map(Raml::yamlText)
          .orElse(null));
      List<String> enums = parameter.enums();
      if (enums.size() > 0) {
        p.setType(RamlType.STRING);
        p.setEnum(enums);
      } else {
        p.setType(raml.define(parameter.type()));
      }
      p.setRequired(!parameter.optional());
      p.setDefault(parameter.defaultValue());
    };

    /** Default consumes/produces: */
    Set<String> alltypes = new LinkedHashSet<>();
    Consumer<Function<RouteMethod, List<String>>> mediaTypes = types ->
        routes.stream().forEach(r -> types.apply(r).forEach(alltypes::add));
    mediaTypes.accept(RouteMethod::consumes);
    mediaTypes.accept(RouteMethod::produces);
    boolean defaultMediaType = false;
    if (alltypes.size() == 0) {
      raml.setMediaType(ImmutableList.of(MediaType.json.name()));
      defaultMediaType = true;
    } else if (alltypes.size() == 1) {
      raml.setMediaType(ImmutableList.of(alltypes.iterator().next()));
      defaultMediaType = true;
    }

    for (RouteMethod route : routes) {
      List<String> segments = Splitter.on("/")
          .trimResults()
          .omitEmptyStrings()
          .splitToList(route.pattern());
      RamlPath path = null;
      for (String segment : segments) {
        RamlPath newPath = pathFactory.apply(path, "/" + segment);
        if (segment.startsWith("{") && segment.endsWith("}")) {
          String pathvar = segment.substring(1, segment.length() - 1);
          route.parameters().stream()
              .filter(it -> it.kind() == RouteParameter.Kind.PATH)
              .filter(it -> it.name().equals(pathvar))
              .findFirst()
              .ifPresent(it -> parameterFactory.accept(newPath::uriParameter, it));
        }
        path = newPath;
      }
      path = Optional.ofNullable(path).orElseGet(() -> raml.path("/"));
      path.setDescription(route.summary()
          .map(Raml::yamlText)
          .orElse(null));
      RamlMethod method = path.method(route.method());
      method.setDescription(route.description()
          .map(Raml::yamlText)
          .orElse(null));

      /** Check for files, if we find one use multipart to render them: */
      List<RouteParameter> files = route.parameters().stream()
          .filter(it -> it.kind() == RouteParameter.Kind.FILE)
          .collect(Collectors.toList());
      if (files.size() > 0) {
        route.parameters().stream()
            .filter(it -> it.kind() == RouteParameter.Kind.QUERY)
            .forEach(it -> parameterFactory.accept(method::formParameter, it));
        files.forEach(it -> {
          parameterFactory.accept(method::formParameter, it);
          method.setMediaType(ImmutableList.of(MediaType.multipart.name()));
        });
      } else {
        route.parameters().stream()
            .filter(it -> it.kind() == RouteParameter.Kind.QUERY)
            .forEach(it -> parameterFactory.accept(method::queryParameter, it));
      }
      /** Consumes: */
      List<String> consumes = route.consumes();
      if (consumes.size() == 0 && !defaultMediaType) {
        consumes = ImmutableList.of(MediaType.json.name());
      }
      method.setMediaType(consumes);

      /** Headers: */
      route.parameters().stream()
          .filter(it -> it.kind() == RouteParameter.Kind.HEADER)
          .forEach(it -> parameterFactory.accept(method::headerParameter, it));

      /** Body: */
      route.parameters().stream()
          .filter(it -> it.kind() == RouteParameter.Kind.BODY)
          .forEach(it -> {
            method.setMediaType(route.consumes());
            method.setBody(raml.define(it.type()));
          });
      /** Response: */
      List<String> produces = route.produces();
      if (produces.size() == 0) {
        produces = ImmutableList.of(MediaType.json.name());
      }
      RouteResponse returns = route.response();
      Map<Integer, String> status = returns.status();
      Integer statusCode = returns.statusCode();
      RamlResponse response = method.response(statusCode);
      response.setDescription(yamlText(returns.description().orElseGet(() -> FriendlyTypeName
          .name(returns.type()))));
      produces.forEach(type -> response.setMediaType(type, raml.define(returns.type())));
      status.entrySet().stream()
          .filter(it -> !statusCode.equals(it.getKey()))
          .forEach(it -> method.response(it.getKey()).setDescription(it.getValue()));
    }

    return raml;
  }

  static String yamlText(String text) {
    return Optional.ofNullable(text).map(lines ->
        Splitter.on("\n")
            .trimResults()
            .omitEmptyStrings()
            .splitToList(lines)
            .stream()
            .collect(Collectors.joining("\n"))
    ).orElse(null);
  }
}
