// 
// Decompiled by Procyon v0.6.0
// 

package com.hypixel.hytale.codec.function;

import com.hypixel.hytale.codec.schema.config.Schema;
import com.hypixel.hytale.codec.schema.SchemaContext;
import java.io.IOException;
import com.hypixel.hytale.codec.util.RawJsonReader;
import com.hypixel.hytale.codec.ExtraInfo;
import org.bson.BsonValue;
import java.util.Objects;
import java.util.function.Function;
import javax.annotation.Nonnull;
import com.hypixel.hytale.codec.Codec;

@Deprecated
public class FunctionCodec<T, R> implements Codec<R>
{
    @Nonnull
    private final Codec<T> codec;
    @Nonnull
    private final Function<T, R> decode;
    @Nonnull
    private final Function<R, T> encode;
    
    public FunctionCodec(final Codec<T> codec, final Function<T, R> decode, final Function<R, T> encode) {
        this.codec = Objects.requireNonNull(codec, "codec parameter can't be null");
        this.decode = Objects.requireNonNull(decode, "decode parameter can't be null");
        this.encode = Objects.requireNonNull(encode, "encode parameter can't be null");
    }
    
    @Nonnull
    @Override
    public R decode(final BsonValue bsonValue, final ExtraInfo extraInfo) {
        final T decode = this.codec.decode(bsonValue, extraInfo);
        final R value = this.decode.apply(decode);
        if (value == null) {
            throw new IllegalArgumentException("Failed to apply function to '" + String.valueOf(decode) + "' decoded from '" + String.valueOf(bsonValue) + "'!");
        }
        return value;
    }
    
    @Override
    public BsonValue encode(final R r, final ExtraInfo extraInfo) {
        return this.codec.encode(this.encode.apply(r), extraInfo);
    }
    
    @Nonnull
    @Override
    public R decodeJson(@Nonnull final RawJsonReader reader, final ExtraInfo extraInfo) throws IOException {
        final T decode = this.codec.decodeJson(reader, extraInfo);
        final R value = this.decode.apply(decode);
        if (value == null) {
            throw new IllegalArgumentException("Failed to apply function to '" + String.valueOf(decode) + "'!");
        }
        return value;
    }
    
    @Nonnull
    @Override
    public Schema toSchema(@Nonnull final SchemaContext context) {
        return this.codec.toSchema(context);
    }
}
