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

import java.io.IOException;
import java.util.Objects;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

@JsonSerialize(using = DiResource.Serializer.class)
@JsonDeserialize(using = DiResource.Deserializer.class)
public final class DiResource extends KeyBase<String> {
    @Nullable
    private final DiService service;
    @NotNull
    private final String name;
    @Nullable
    private final String description;
    private final DiResourceType type;
    @NotNull
    private final DiQuotingMode mode;
    @Nullable
    private final String groupKey;
    @Nullable
    private final Integer priority;

    @NotNull
    public static Builder withKey(@NotNull final String key) {
        return new Builder(key);
    }

    private DiResource(@NotNull final BuilderBase<?> builder) {
        super(builder.getKey());
        service = builder.service;
        name = ValidationUtils.requireNonNull(builder.name, "Name is required");
        description = builder.description;
        type = builder.type;
        mode = builder.mode;
        groupKey = builder.groupKey;
        priority = builder.priority;
    }

    @NotNull
    public DiService getService() {
        return Objects.requireNonNull(service, "No service!");
    }

    @NotNull
    public String getName() {
        return name;
    }

    @Nullable
    public String getDescription() {
        return description;
    }

    public DiResourceType getType() {
        return type;
    }

    @NotNull
    public DiQuotingMode getQuotingMode() {
        return mode;
    }

    @Nullable
    public String getGroup() {
        return groupKey;
    }

    @Nullable
    public Integer getPriority() {
        return priority;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }
        final DiResource resource = (DiResource) o;
        return Objects.equals(getService(), resource.getService());
    }

    public static abstract class BuilderBase<B extends BuilderBase<B>> extends KeyBase.Builder<String, B> {
        @Nullable
        protected DiService service;
        @Nullable
        protected String name;
        @Nullable
        protected String description;
        @Nullable
        protected DiResourceType type;
        @NotNull
        private DiQuotingMode mode = DiQuotingMode.DEFAULT;
        @Nullable
        protected String groupKey;
        @Nullable
        private Integer priority;

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

        @NotNull
        public B inService(@NotNull final DiService service) {
            this.service = service;
            return self();
        }

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

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

        @NotNull
        public B withType(final DiResourceType type) {
            this.type = type;
            return self();
        }

        @NotNull
        public B inMode(@NotNull final DiQuotingMode mode) {
            this.mode = mode;
            return self();
        }

        @NotNull
        public B inGroup(@Nullable final String group) {
            this.groupKey = group;
            return self();
        }

        @NotNull
        public B withPriority(@Nullable final Integer priority) {
            this.priority = priority;
            return self();
        }

        @NotNull
        protected DiResource buildResource() {
            return new DiResource(this);
        }
    }

    public static final class Builder extends BuilderBase<Builder> implements DtoBuilder<DiResource> {
        private Builder(@NotNull final String key) {
            super(key);
        }

        @NotNull
        @Override
        public DiResource build() {
            return buildResource();
        }
    }

    static final class Serializer extends JsonSerializer<DiResource> {
        @Override
        public void serialize(@NotNull final DiResource resource,
                              @NotNull final JsonGenerator jg,
                              @NotNull final SerializerProvider sp) throws IOException {
            jg.writeStartObject();
            jg.writeStringField("key", resource.getKey());
            if (resource.service != null) {
                jg.writeObjectField("service", resource.getService());
            }
            jg.writeStringField("name", resource.getName());
            if (resource.getDescription() != null) {
                jg.writeStringField("description", resource.getDescription());
            }
            if (resource.getType() != null) {
                jg.writeStringField("type", resource.getType().name());
            }
            jg.writeObjectField("quotingMode", resource.getQuotingMode());
            jg.writeObjectField("group", resource.getGroup());
            jg.writeObjectField("priority", resource.getPriority());
            jg.writeEndObject();
        }
    }

    static final class Deserializer extends JsonDeserializerBase<DiResource> {
        @Override
        public DiResource deserialize(@NotNull final JsonParser jp,
                                      @NotNull final DeserializationContext dc) throws IOException {
            final JsonNode node = jp.getCodec().readTree(jp);
            final JsonNode priority = node.get("priority");
            final Builder builder = new Builder(node.get("key").asText())
                    .withName(node.get("name").asText())
                    .withDescription(node.has("description") ? node.get("description").asText() : null)
                    .withType(node.hasNonNull("type") ?
                            DiResourceType.valueOf(node.get("type").asText()) : null)
                    .inMode(node.hasNonNull("quotingMode") ?
                            DiQuotingMode.valueOf(node.get("quotingMode").asText()) : DiQuotingMode.DEFAULT)
                    .inGroup(node.has("group") && !node.get("group").isNull() ? node.get("group").asText() : null)
                    .withPriority(priority == null || priority.isNull() ? null : priority.asInt());
            if (node.has("service")) {
                builder.inService(SerializationUtils.convertValue(node.get("service"), DiService.class));
            }
            return builder.build();
        }
    }
}
