package net.minecraft.util.datafix.fixes;

import com.mojang.datafixers.DSL;
import com.mojang.datafixers.DataFix;
import com.mojang.datafixers.OpticFinder;
import com.mojang.datafixers.TypeRewriteRule;
import com.mojang.datafixers.Typed;
import com.mojang.datafixers.schemas.Schema;
import com.mojang.datafixers.types.Type;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.DynamicOps;
import java.util.Optional;
import net.minecraft.Util;
import net.minecraft.util.datafix.ExtraDataFixUtils;
import net.minecraft.util.datafix.LegacyComponentDataFixUtils;
import net.minecraft.util.datafix.schemas.NamespacedSchema;

public class EntityCustomNameToComponentFix extends DataFix {
    public EntityCustomNameToComponentFix(Schema outputSchema) {
        super(outputSchema, true);
    }

    @Override
    public TypeRewriteRule makeRule() {
        Type<?> type = this.getInputSchema().getType(References.ENTITY);
        Type<?> type1 = this.getOutputSchema().getType(References.ENTITY);
        OpticFinder<String> opticFinder = DSL.fieldFinder("id", NamespacedSchema.namespacedString());
        OpticFinder<String> opticFinder1 = (OpticFinder<String>)type.findField("CustomName");
        Type<?> type2 = type1.findFieldType("CustomName");
        return this.fixTypeEverywhereTyped("EntityCustomNameToComponentFix", type, type1, typed -> fixEntity(typed, type1, opticFinder, opticFinder1, type2));
    }

    private static <T> Typed<?> fixEntity(Typed<?> typed, Type<?> type, OpticFinder<String> opticFinder, OpticFinder<String> opticFinder1, Type<T> type1) {
        Optional<String> optional = typed.getOptional(opticFinder1);
        if (optional.isEmpty()) {
            return ExtraDataFixUtils.cast(type, typed);
        } else if (optional.get().isEmpty()) {
            return Util.writeAndReadTypedOrThrow(typed, type, dynamic1 -> dynamic1.remove("CustomName"));
        } else {
            String string = typed.getOptional(opticFinder).orElse("");
            Dynamic<?> dynamic = fixCustomName(typed.getOps(), optional.get(), string);
            return typed.set(opticFinder1, Util.readTypedOrThrow(type1, dynamic));
        }
    }

    private static <T> Dynamic<T> fixCustomName(DynamicOps<T> ops, String customName, String id) {
        return "minecraft:commandblock_minecart".equals(id)
            ? new Dynamic<>(ops, ops.createString(customName))
            : LegacyComponentDataFixUtils.createPlainTextComponent(ops, customName);
    }
}
