package ru.yandex.qe.dispenser.client.v1.impl;

import org.apache.cxf.jaxrs.client.WebClient;
import org.jetbrains.annotations.NotNull;

import ru.yandex.qe.dispenser.api.v1.DiOrder;

public abstract class ProjectFilter extends RequestFilter {
    @NotNull
    public static ProjectFilter single(@NotNull final String projectKey) {
        return new ProjectFilter.Key(projectKey);
    }

    @NotNull
    public static ProjectFilter onlyLeafs() {
        return Leaf.INSTANCE;
    }

    @NotNull
    public static ProjectFilter responsible(@NotNull final String login) {
        return new Person("responsible", login);
    }

    @NotNull
    public static ProjectFilter member(@NotNull final String login) {
        return new Person("member", login);
    }

    public static ProjectFilter showPersons(final boolean showPersons) {
        return new ProjectFilter() {
            @Override
            @NotNull
            WebClient apply(@NotNull final WebClient client) {
                return client.query("showPersons", "" + showPersons);
            }
        };
    }

    @NotNull
    public static ProjectFilter order(@NotNull final DiOrder order) {
        return new Order(order);
    }

    private static final class Key extends ProjectFilter {
        @NotNull
        private final String projectKey;

        private Key(@NotNull final String projectKey) {
            this.projectKey = projectKey;
        }

        @NotNull
        @Override
        WebClient apply(@NotNull final WebClient client) {
            return client.query("project", projectKey);
        }
    }

    private static final class Leaf extends ProjectFilter {
        private static final Leaf INSTANCE = new Leaf();

        @NotNull
        @Override
        WebClient apply(@NotNull final WebClient client) {
            return client.query("leaf", true);
        }
    }

    private static final class Order extends ProjectFilter {
        @NotNull
        private final DiOrder orderParam;

        private Order(@NotNull final DiOrder orderParam) {
            this.orderParam = orderParam;
        }

        @Override
        @NotNull WebClient apply(@NotNull WebClient client) {
            return client.query("order", orderParam);
        }
    }

    private static final class Person extends ProjectFilter {
        @NotNull
        private final String paramName;
        @NotNull
        private final String login;

        private Person(@NotNull final String paramName, @NotNull final String login) {
            this.paramName = paramName;
            this.login = login;
        }

        @NotNull
        @Override
        WebClient apply(@NotNull final WebClient client) {
            return client.query(paramName, login);
        }
    }
}
