/*
   * (non-Javadoc)
   * @see org.springframework.hateoas.hal.CurieProvider#getNamespacedRelFrom(java.lang.String)
   */
  @Override
  public String getNamespacedRelFor(String rel) {

    boolean prefixingNeeded =
        defaultCurie != null && !IanaRels.isIanaRel(rel) && !rel.contains(":");
    return prefixingNeeded ? String.format("%s:%s", defaultCurie.name, rel) : rel;
  }
  @Override
  public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider)
      throws IOException {

    try {
      Collection<Link> simpleLinks = new ArrayList<Link>();
      Collection<Affordance> affordances = new ArrayList<Affordance>();
      Collection<Link> templatedLinks = new ArrayList<Link>();
      Collection<Affordance> templatedAffordances = new ArrayList<Affordance>();
      Collection<Affordance> collectionAffordances = new ArrayList<Affordance>();
      Link selfRel = null;
      for (Link link : links) {
        if (link instanceof Affordance) {
          final Affordance affordance = (Affordance) link;
          final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
          if (!actionDescriptors.isEmpty()) {
            if (affordance.isTemplated()) {
              templatedAffordances.add(affordance);
            } else {
              if (!affordance.isSelfRel()
                  && Cardinality.COLLECTION == affordance.getCardinality()) {
                collectionAffordances.add(affordance);
              } else {
                affordances.add(affordance);
              }
            }
          } else {
            if (affordance.isTemplated()) {
              templatedLinks.add(affordance);
            } else {
              simpleLinks.add(affordance);
            }
          }
        } else if (link.isTemplated()) {
          templatedLinks.add(link);
        } else {
          simpleLinks.add(link);
        }
        if ("self".equals(link.getRel())) {
          selfRel = link;
        }
      }

      for (Affordance templatedAffordance : templatedAffordances) {
        jgen.writeObjectFieldStart(templatedAffordance.getRel());

        jgen.writeStringField("@type", "hydra:IriTemplate");
        jgen.writeStringField("hydra:template", templatedAffordance.getHref());
        final List<ActionDescriptor> actionDescriptors = templatedAffordance.getActionDescriptors();
        ActionDescriptor actionDescriptor = actionDescriptors.get(0);
        jgen.writeArrayFieldStart("hydra:mapping");
        writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getPathVariableNames());
        writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getRequestParamNames());
        jgen.writeEndArray();

        jgen.writeEndObject();
      }
      for (Link templatedLink : templatedLinks) {
        // we only have the template, no access to method params
        jgen.writeObjectFieldStart(templatedLink.getRel());

        jgen.writeStringField("@type", "hydra:IriTemplate");
        jgen.writeStringField("hydra:template", templatedLink.getHref());

        jgen.writeArrayFieldStart("hydra:mapping");
        writeHydraVariableMapping(jgen, null, templatedLink.getVariableNames());
        jgen.writeEndArray();

        jgen.writeEndObject();
      }

      @SuppressWarnings("unchecked")
      Deque<LdContext> contextStack =
          (Deque<LdContext>) serializerProvider.getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT);
      String currentVocab =
          (contextStack != null && !contextStack.isEmpty()) ? contextStack.peek().vocab : null;

      // related collections
      if (!collectionAffordances.isEmpty()) {
        jgen.writeArrayFieldStart("hydra:collection");

        for (Affordance collectionAffordance : collectionAffordances) {
          jgen.writeStartObject();
          jgen.writeStringField(JsonLdKeywords.AT_TYPE, "hydra:Collection");
          jgen.writeStringField(JsonLdKeywords.AT_ID, collectionAffordance.getHref());
          jgen.writeObjectFieldStart("hydra:manages");
          jgen.writeStringField("hydra:property", collectionAffordance.getRel());
          // a) in the case of </Alice> :knows /bob the subject must be /Alice
          // b) in the case of <> orderedItem /latte-1 the subject is an anonymous resource of type
          // Order
          // c) in the case of </order/1> :seller </store> the object must be the store
          // 1. where is the information *about* the subject or object: the type or @id
          // 2. how to decide if the collection manages items for a subject or object?
          // ad 1.)
          // ad a) self rel of the Resource that has the collection affordance: looking through link
          // list
          //       at serialization time is possible
          // ad b) a candidate is the class given as value of @ExposesResourceFor on the controller
          //       that defines the method which leads us to believe we have a collection:
          //       either a GET /orders handler having a collection return type or the POST /orders.
          //       Works only if the GET or POST has no request mapping path of its own
          //       an alternative is to use {} without type if @ExposesResourceFor is not present
          // ad c) like a
          // ad 2.)
          // we know the affordance is a collection
          // * we could pass information into build(rel), like
          // .rel().reverseRel("schema:seller").build()
          // * we could use build("myReversedTerm") and look at the @context to see if it is
          // reversed,
          //   if so, we know that the manages block must use object not subject. However weird if
          // the
          //   reverse term is never really used in the json-ld
          // * we could have a registry which says if a property is meant to be reversed in a
          // certain context
          //   and use that to find out if we need subject or object, like :seller ->
          if (selfRel != null) {
            // prefer rev over rel, assuming that rev exists to be used by RDF serialization
            if (collectionAffordance.getRev() != null) {
              jgen.writeStringField("hydra:object", selfRel.getHref());
            } else if (collectionAffordance.getRel() != null) {
              jgen.writeStringField("hydra:subject", selfRel.getHref());
            }
          } else {
            // prefer rev over rel, assuming that rev exists to be used by RDF serialization
            if (collectionAffordance.getRev() != null) {
              jgen.writeObjectFieldStart("hydra:object");
              jgen.writeEndObject();
            } else if (collectionAffordance.getRel() != null) {
              jgen.writeObjectFieldStart("hydra:subject");
              jgen.writeEndObject();
            }
          }
          jgen.writeEndObject(); // end manages

          List<ActionDescriptor> actionDescriptors = collectionAffordance.getActionDescriptors();
          if (!actionDescriptors.isEmpty()) {
            jgen.writeArrayFieldStart("hydra:operation");
          }
          writeActionDescriptors(jgen, currentVocab, actionDescriptors);
          if (!actionDescriptors.isEmpty()) {
            jgen.writeEndArray(); // end hydra:operation
          }

          jgen.writeEndObject(); // end collection
        }
        jgen.writeEndArray();
      }

      for (Affordance affordance : affordances) {
        final String rel = affordance.getRel();
        List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();

        if (!actionDescriptors.isEmpty()) {
          if (!Link.REL_SELF.equals(rel)) {
            jgen.writeObjectFieldStart(rel); // begin rel
          }
          jgen.writeStringField(JsonLdKeywords.AT_ID, affordance.getHref());
          jgen.writeArrayFieldStart("hydra:operation");
        }

        writeActionDescriptors(jgen, currentVocab, actionDescriptors);

        if (!actionDescriptors.isEmpty()) {
          jgen.writeEndArray(); // end hydra:operation

          if (!Link.REL_SELF.equals(rel)) {
            jgen.writeEndObject(); // end rel
          }
        }
      }

      for (Link simpleLink : simpleLinks) {
        final String rel = simpleLink.getRel();
        if (Link.REL_SELF.equals(rel)) {
          jgen.writeStringField("@id", simpleLink.getHref());
        } else {
          String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel;
          jgen.writeObjectFieldStart(linkAttributeName);
          jgen.writeStringField("@id", simpleLink.getHref());
          jgen.writeEndObject();
        }
      }
    } catch (IntrospectionException e) {
      throw new RuntimeException(e);
    }
  }