package net.ranides.assira.ui.query;

import net.ranides.assira.collection.arrays.ArrayUtils;

import java.awt.*;
import java.util.Arrays;
import java.util.function.Consumer;

public class IComponentSelector {

    private final IComponents scope;

    private final String[] path;

    IComponentSelector(IComponents scope, String[] path) {
        this.scope = scope;
        this.path = path;
    }

    public static IComponentSelector of(String path) {
        return of(IComponentUtils.windows(), path);
    }

    public static IComponentSelector of(IComponent scope, String path) {
        return of(IComponents.of(scope), path);
    }

    public static IComponentSelector of(IComponents scope, String path) {
        return new IComponentSelector(scope, path.split("[ ./]+"));
    }

    public IComponents scope() {
        return scope;
    }

    public String[] path() {
        return path;
    }

    public IComponentSelector parent() {
        return new IComponentSelector(scope, ArrayUtils.head(path, path.length-1));
    }

    public IComponents stream() {
        return scope().find(path);
    }

    public void forEach(Consumer<? super IComponent> consumer) {
        stream().forEach(consumer);
    }

    public IComponent first() {
        return stream().first().orElseThrow(() -> {
            return new IllegalArgumentException(Arrays.toString(path) + " does not match any component");
        });
    }

    public <T extends Component> T first(Class<T> type) {
        return stream().first(type).orElseThrow(() -> {
            return new IllegalArgumentException(Arrays.toString(path) + " does not match any " + type);
        });
    }
}
