package ru.yandex.qe.dispenser.ws.param;

import org.jetbrains.annotations.NotNull;

import ru.yandex.qe.dispenser.domain.QuotaSpec;
import ru.yandex.qe.dispenser.domain.Resource;
import ru.yandex.qe.dispenser.domain.Service;
import ru.yandex.qe.dispenser.domain.hierarchy.Hierarchy;

public final class QuotaSpecFilterParam extends ComplexParam<QuotaSpec> {
    @NotNull
    private final QuotaSpec quotaSpec;

    public QuotaSpecFilterParam(@NotNull final String serciceResourceSpecKey) {
        final String[] parts = serciceResourceSpecKey.split("/");
        if (parts.length < 3 || parts.length > 4) {
            throw new IllegalArgumentException(
                    "Expected: &quota spec key: /{serviceKey}/{resourceKey}[/{quotaSpecKey}], found: " + serciceResourceSpecKey);
        }
        final Service service = Hierarchy.get().getServiceReader().read(parts[1]);
        final Resource resource = resource(service, parts[2]);

        if (parts.length == 3) {
            quotaSpec = Hierarchy.get().getQuotaSpecReader().readSingle(resource);
        } else {
            quotaSpec = Hierarchy.get().getQuotaSpecReader().read(new QuotaSpec.Key(parts[3], resource));
        }
    }

    @NotNull
    @Override
    public QuotaSpec get() {
        return quotaSpec;
    }

    @Override
    public String toString() {
        final Resource resource = quotaSpec.getResource();
        return String.format("/%s/%s/%s", resource.getService().getKey(), resource.getKey().getPublicKey(), quotaSpec.getKey().getPublicKey());
    }
}
