package net.minecraft.network.chat;

import java.util.stream.Collector;
import com.google.common.collect.ImmutableMap;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.Objects;
import javax.annotation.Nullable;
import net.minecraft.ChatFormatting;
import java.util.Map;

public final class TextColor {
    private static final Map<ChatFormatting, TextColor> LEGACY_FORMAT_TO_COLOR;
    private static final Map<String, TextColor> NAMED_COLORS;
    private final int value;
    @Nullable
    private final String name;
    
    private TextColor(final int integer, final String string) {
        this.value = integer;
        this.name = string;
    }
    
    private TextColor(final int integer) {
        this.value = integer;
        this.name = null;
    }
    
    public int getValue() {
        return this.value;
    }
    
    public String serialize() {
        if (this.name != null) {
            return this.name;
        }
        return this.formatValue();
    }
    
    private String formatValue() {
        return String.format("#%06X", this.value);
    }
    
    @Override
    public boolean equals(final Object object) {
        if (this == object) {
            return true;
        }
        if (object == null || this.getClass() != object.getClass()) {
            return false;
        }
        final TextColor nc3 = (TextColor)object;
        return this.value == nc3.value;
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(this.value, this.name);
    }
    
    @Override
    public String toString() {
        return (this.name != null) ? this.name : this.formatValue();
    }
    
    @Nullable
    public static TextColor fromLegacyFormat(final ChatFormatting i) {
        return TextColor.LEGACY_FORMAT_TO_COLOR.get(i);
    }
    
    public static TextColor fromRgb(final int integer) {
        return new TextColor(integer);
    }
    
    @Nullable
    public static TextColor parseColor(final String string) {
        if (string.startsWith("#")) {
            try {
                final int integer2 = Integer.parseInt(string.substring(1), 16);
                return fromRgb(integer2);
            }
            catch (NumberFormatException numberFormatException2) {
                return null;
            }
        }
        return TextColor.NAMED_COLORS.get(string);
    }
    
    static {
        LEGACY_FORMAT_TO_COLOR = Stream.<ChatFormatting>of(ChatFormatting.values()).filter(ChatFormatting::isColor).collect(ImmutableMap.toImmutableMap(Function.identity(), i -> new TextColor(i.getColor(), i.getName())));
        NAMED_COLORS = TextColor.LEGACY_FORMAT_TO_COLOR.values().stream().collect(ImmutableMap.toImmutableMap(nc -> nc.name, Function.identity()));
    }
}
