package org.ccci.gto.android.common.jsonapi.retrofit2;

import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ForwardingMap;

import java.util.HashMap;
import java.util.Map;

public abstract class BaseJsonApiParams<T extends BaseJsonApiParams> extends ForwardingMap<String, String> {
    @VisibleForTesting
    static final String PARAM_INCLUDE = "include";
    private static final String PARAM_FIELDS = "fields";

    private static final Joiner INCLUDE_JOINER = Joiner.on(",").skipNulls();

    private final Map<String, String> mParams = new HashMap<>();

    @Override
    protected Map<String, String> delegate() {
        return mParams;
    }

    @NonNull
    protected abstract T self();

    @NonNull
    public final T include(final String... paths) {
        put(PARAM_INCLUDE, INCLUDE_JOINER.join(Strings.emptyToNull(get(PARAM_INCLUDE)), null, (Object[]) paths));
        return self();
    }

    @NonNull
    public final T clearIncludes() {
        remove(PARAM_INCLUDE);
        return self();
    }

    @NonNull
    public final T fields(@NonNull final String type, @NonNull final String... fields) {
        final String param = PARAM_FIELDS + "[" + type + "]";
        put(param, INCLUDE_JOINER.join(Strings.emptyToNull(get(param)), null, (Object[]) fields));
        return self();
    }

    public final T clearFields(@NonNull final String type) {
        remove(PARAM_FIELDS + "[" + type + "]");
        return self();
    }
}

@@ -53,91 +53,8 @@
 2;%0A%0A
-import androidx.annotation.NonNull;%0Aimport androidx.annotation.VisibleForTesting;%0A%0A
 impo
@@ -224,16 +224,99 @@
 l.Map;%0A%0A
+import androidx.annotation.NonNull;%0Aimport androidx.annotation.VisibleForTesting;%0A%0A
 public a
@@ -546,16 +546,69 @@
 fields%22;
+%0A    private static final String PARAM_SORT = %22sort%22;
 %0A%0A    pr
@@ -633,23 +633,19 @@
  Joiner 
-INCLUDE
+CSV
 _JOINER 
@@ -972,23 +972,19 @@
 NCLUDE, 
-INCLUDE
+CSV
 _JOINER.
@@ -1379,23 +1379,19 @@
 (param, 
-INCLUDE
+CSV
 _JOINER.
@@ -1623,11 +1623,146 @@
 );%0A    %7D
+%0A%0A    public final T sort(@NonNull final String... keys) %7B%0A        put(PARAM_SORT, CSV_JOINER.join(keys));%0A        return self();%0A    %7D
 %0A%7D%0A

add the jsonapi sort command to BaseJsonApiParams