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

package org.bson.codecs;

import org.bson.BsonReader;
import org.bson.BsonInvalidOperationException;
import org.bson.types.ObjectId;
import org.bson.BsonWriter;
import org.bson.codecs.configuration.CodecConfigurationException;
import org.bson.BsonType;

public class StringCodec implements Codec<String>, RepresentationConfigurable<String>
{
    private BsonType representation;
    
    public StringCodec() {
        this.representation = BsonType.STRING;
    }
    
    private StringCodec(final BsonType representation) {
        this.representation = representation;
    }
    
    @Override
    public BsonType getRepresentation() {
        return this.representation;
    }
    
    @Override
    public Codec<String> withRepresentation(final BsonType representation) {
        if (representation != BsonType.OBJECT_ID && representation != BsonType.STRING) {
            throw new CodecConfigurationException(representation + " is not a supported representation for StringCodec");
        }
        return new StringCodec(representation);
    }
    
    @Override
    public void encode(final BsonWriter writer, final String value, final EncoderContext encoderContext) {
        switch (this.representation) {
            case STRING: {
                writer.writeString(value);
                break;
            }
            case OBJECT_ID: {
                writer.writeObjectId(new ObjectId(value));
                break;
            }
            default: {
                throw new BsonInvalidOperationException("Cannot encode a String to a " + this.representation);
            }
        }
    }
    
    @Override
    public String decode(final BsonReader reader, final DecoderContext decoderContext) {
        switch (this.representation) {
            case STRING: {
                if (reader.getCurrentBsonType() == BsonType.SYMBOL) {
                    return reader.readSymbol();
                }
                return reader.readString();
            }
            case OBJECT_ID: {
                return reader.readObjectId().toHexString();
            }
            default: {
                throw new CodecConfigurationException("Cannot decode " + this.representation + " to a String");
            }
        }
    }
    
    @Override
    public Class<String> getEncoderClass() {
        return String.class;
    }
}
