package ru.yandex.qe.dispenser.api.v1;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.jetbrains.annotations.NotNull;

import ru.yandex.qe.dispenser.api.DtoBuilder;
import ru.yandex.qe.dispenser.api.KeyBase;
import ru.yandex.qe.dispenser.api.util.JsonDeserializerBase;

@JsonDeserialize(using = DiSegmentation.Deserializer.class)
public final class DiSegmentation extends KeyBase<String> {
    private final String name;
    private final String description;
    private final int priority;

    private DiSegmentation(@NotNull final Builder builder) {
        super(builder.getKey());
        name = builder.name;
        description = builder.description;
        priority = builder.priority;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public int getPriority() {
        return priority;
    }

    public static abstract class BuilderBase<B extends BuilderBase<B>> extends KeyBase.Builder<String, B> {
        protected String name;
        protected String description;
        protected int priority;

        protected BuilderBase(@NotNull final String key) {
            super(key);
        }

        public B withName(@NotNull final String name) {
            this.name = name;
            return self();
        }

        public B withDescription(@NotNull final String description) {
            this.description = description;
            return self();
        }

        public B withPriority(final int priority) {
            this.priority = priority;
            return self();
        }

    }

    public static final class Builder extends DiSegmentation.BuilderBase<Builder> implements DtoBuilder<DiSegmentation> {

        public Builder(final @NotNull String key) {
            super(key);
        }

        @NotNull
        @Override
        public DiSegmentation build() {
            return new DiSegmentation(this);
        }
    }

    static final class Deserializer extends JsonDeserializerBase<DiSegmentation> {
        @NotNull
        @Override
        public DiSegmentation deserialize(@NotNull final JsonParser jp,
                                          @NotNull final DeserializationContext dc) throws IOException {
            final JsonNode json = toJson(jp);
            return new Builder(json.get("key").asText())
                    .withName(json.get("name").asText())
                    .withDescription(json.get("description").asText())
                    .withPriority(json.get("priority").asInt())
                    .build();
        }
    }
}
