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

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import ru.yandex.qe.dispenser.domain.Entity;
import ru.yandex.qe.dispenser.domain.EntitySpec;
import ru.yandex.qe.dispenser.domain.Service;
import ru.yandex.qe.dispenser.domain.dao.entity.EntityDao;
import ru.yandex.qe.dispenser.domain.hierarchy.Hierarchy;
import ru.yandex.qe.dispenser.domain.util.ApplicationContextProvider;

public final class EntityFilterParam extends ComplexParam<Entity> {
    @Nullable
    private final Entity entity;

    public EntityFilterParam(@NotNull final String entityPath) {
        final String[] parts = entityPath.split("/");
        if (parts.length != 4) {
            throw new IllegalArgumentException("Expected: &resource key: /{serviceKey}/{entitySpecKey}/{entityKey}, found: " + entityPath);
        }
        final Service service = Hierarchy.get().getServiceReader().read(parts[1]);
        final EntitySpec spec = Hierarchy.get().getEntitySpecReader().read(new EntitySpec.Key(parts[2], service));

        final EntityDao entityDao = ApplicationContextProvider.getContext().getBean(EntityDao.class);
        entity = entityDao.readOrNull(new Entity.Key(parts[3], spec));
    }

    @Nullable
    @Override
    public Entity get() {
        return entity;
    }
}
