package ru.yandex.direct.proxy.model.web.callstep;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import ru.yandex.direct.proxy.model.web.callstep.specialserializers.CallStepResultJsonSerializationFacade;

@JsonSerialize(using = CallStepSuccessResponse.CallStepSuccessResponseSerializer.class)
public class CallStepSuccessResponse implements CallStepResponse {
    public static final String RESULT = "result";

    @JsonProperty(RESULT)
    private Object result;

    @Override
    public boolean isSuccessful() {
        return true;
    }

    public Object getResult() {
        return result;
    }

    public CallStepSuccessResponse withResult(Object result) {
        this.result = result;
        return this;
    }

    public static class CallStepSuccessResponseSerializer extends JsonSerializer<CallStepSuccessResponse> {
        CallStepResultJsonSerializationFacade callStepResultJsonSerializationFacade;

        public CallStepSuccessResponseSerializer() {
            super();
            this.callStepResultJsonSerializationFacade = new CallStepResultJsonSerializationFacade();
        }

        @Override
        public void serialize(CallStepSuccessResponse value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException
        {
            gen.writeStartObject();
            gen.writeObjectField(IS_SUCCESSFULL, value.isSuccessful());

            Object result = value.getResult();

            if (!callStepResultJsonSerializationFacade.hasSerializer(result)) {
                gen.writeObjectField(RESULT, result);
            } else {
                callStepResultJsonSerializationFacade.getSerializer(result)
                        .serialize(result, gen, serializers);
            }
            gen.writeEndObject();
        }
    }
}
