package com.utopiaindustries.qualitychecker.utils.jackson;

import android.os.Build;

import androidx.annotation.RequiresApi;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.utopiaindustries.qualitychecker.utils.DateTimeUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

	private static final long serialVersionUID = 1L;

	@RequiresApi(api = Build.VERSION_CODES.O)
    public LocalDateTimeDeserializer() {
		super( LocalDateTime.class );
	}

	@RequiresApi(api = Build.VERSION_CODES.O)
    @Override
	public LocalDateTime deserialize( JsonParser parser, DeserializationContext ctxt ) throws IOException, JsonProcessingException {
		JsonNode node = parser.getCodec().readTree( parser );
		String dateStr = node.asText();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern( DateTimeUtils.HTML5_DATETIME_INPUT_FORMAT_WITH_SECONDS );
		return LocalDateTime.parse( dateStr, formatter );
	}
}
