package ru.micord.ervu.account_applications.deserializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import ru.micord.ervu.account_applications.model.DataWrapper;

/**
 * @author Adel Kalimullin
 */
public class DataWrapperDeserializer extends JsonDeserializer<DataWrapper> {

  @Override
  public DataWrapper deserialize(JsonParser jsonParser,
      DeserializationContext deserializationContext) throws IOException, JacksonException {
    JsonNode node = jsonParser.readValueAsTree();
    if (node.isTextual()){
      return new DataWrapper(List.of(node.asText()));
    }
    else if (node.isArray()){
      List<String> values = new ArrayList<>();
      for (JsonNode element : node) {
        if (element.isTextual()) {
          values.add(element.asText());
        }
      }
      return new DataWrapper(values);
    }

    return new DataWrapper(Collections.emptyList());
  }
}
