package com.eshore.gringotts.web.domain.base.entity;

import com.eshore.gringotts.web.domain.entity.DataFile;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonDeserialize(using = FileInfo.FileInfoDeserializer.class)
public final class FileInfo {
    private String id;
    private String name;
    private String filename;
    private Long value;
    private String state;

    public FileInfo(DataFile dataFile) {
        this.id = dataFile.getId().toString();
        this.name = dataFile.getFilename();
        this.filename = dataFile.getFilename();
        this.value = dataFile.getId();
        this.state = "uploaded";
    }

    public static final class FileInfoDeserializer extends JsonDeserializer<FileInfo> {
        @Override
        public FileInfo deserialize(JsonParser parser, DeserializationContext context) throws IOException {
            TreeNode root = parser.readValueAsTree();
            if (root instanceof ObjectNode) {
                ObjectNode node = (ObjectNode) root;
                return new FileInfo(
                        node.get("id").asText(),
                        node.get("name").asText(),
                        node.get("filename").asText(),
                        node.get("value").asLong(),
                        node.get("state").asText()
                );
            }
            return null;
        }
    }
}
