package org.implab.gradle.common.json;

import java.util.Arrays;

import groovy.lang.Closure;
import groovy.lang.MissingMethodException;

public interface GroovyObjectSpec extends JsonObjectSpec {

    default void propertyMissing(String name, Object value) {
        set(name, value);
    }

    default Object methodMissing(String name, Object args) {
        Object[] arr = (Object[]) args;

        // author { ... }, repository { ... }
        if (arr.length == 1 && arr[0] instanceof Closure<?>) {
            DefaultJsonObjectSpec spec = new DefaultJsonObjectSpec();
            Closure<?> cl = (Closure<?>) arr[0];
            cl.setDelegate(spec);
            cl.setResolveStrategy(Closure.DELEGATE_FIRST);
            cl.call();
            set(name, spec.toMap());
            return null;
        } else {
            boolean hasClosure = Arrays.stream(arr)
                    .anyMatch(a -> a instanceof Closure<?>);

            if (!hasClosure) {
                set(name, Arrays.asList(arr));
                return null;
            }
        }

        throw new MissingMethodException(name, getClass(), arr);
    }
}
