package xyz.quickbasic.tieredrepairkits.config;

import com.hypixel.hytale.codec.Codec;
import com.hypixel.hytale.codec.codecs.array.ArrayCodec;
import com.hypixel.hytale.codec.schema.SchemaContext;
import com.hypixel.hytale.codec.schema.config.Schema;
import org.bson.BsonValue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RecipeListCodec implements Codec<List<RecipeIngredient>> {

    private final ArrayCodec<RecipeIngredient> arrayCodec = new ArrayCodec<>(RecipeIngredient.CODEC, RecipeIngredient[]::new);

    @Override
    public List<RecipeIngredient> decode(BsonValue bsonValue, com.hypixel.hytale.codec.ExtraInfo extraInfo) {
        try {
            RecipeIngredient[] arr = arrayCodec.decode(bsonValue, extraInfo);
            return arr == null ? new ArrayList<>() : new ArrayList<>(Arrays.asList(arr));
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public BsonValue encode(List<RecipeIngredient> value, com.hypixel.hytale.codec.ExtraInfo extraInfo) {
        return arrayCodec.encode(value.toArray(new RecipeIngredient[0]), extraInfo);
    }

    @Override
    public Schema toSchema(SchemaContext context) {
        return arrayCodec.toSchema(context);
    }
}