package ru.yandex.autotests.directapi.darkside.model.multipliers;

import java.io.IOException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import static com.google.common.base.Preconditions.checkState;

public class BsAtomJsonAdapter extends TypeAdapter<DirectAtom> {
    @Override
    public void write(JsonWriter jsonWriter, DirectAtom bsAtom) throws IOException {
        checkState((bsAtom.getValueInteger() != null) != (bsAtom.getValueString() != null));
        //
        jsonWriter.beginArray();
        jsonWriter.value(bsAtom.getKeyword());
        jsonWriter.value(bsAtom.getOperation());
        if (bsAtom.getValueInteger() != null) {
            jsonWriter.value(bsAtom.getValueInteger());
        } else if (bsAtom.getValueString() != null) {
            jsonWriter.value(bsAtom.getValueString());
        }
        jsonWriter.endArray();
    }

    @Override
    public BsAtom read(JsonReader jsonReader) throws IOException {
        BsAtom bsAtom = new BsAtom();

        jsonReader.beginArray();
        String keyword = jsonReader.nextString();
        bsAtom.withKeyword(keyword);
        bsAtom.withOperation(jsonReader.nextString());
        ExpressionParameter parameterInfo = ExpressionParameter.fromBsValue(keyword);
        JsonToken nextToken = jsonReader.peek();
        switch (nextToken) {
            case STRING: {
                if (parameterInfo.getType() != ExpressionParameterType.STRING) {
                    throw new IllegalStateException("Expected " + parameterInfo.getType() + " but got STRING");
                }
                bsAtom.withValueString(jsonReader.nextString());
                break;
            }
            case NUMBER: {
                if (parameterInfo.getType() != ExpressionParameterType.INTEGER) {
                    throw new IllegalStateException("Expected " + parameterInfo.getType() + " but got NUMBER");
                }
                bsAtom.withValueInteger(jsonReader.nextInt());
                break;
            }
        }
        jsonReader.endArray();
        return bsAtom;
    }
}
