/*
 Copyright 2004-2008 Paul R. Holser, Jr.  All rights reserved.
 Licensed under the Academic Free License version 3.0
 */

package joptsimple.util;

import joptsimple.internal.Strings;

/**
 * <p>A simple string key/string value pair.</p>
 *
 * <p>This is useful as an argument type for options whose values take on the form
 * <kbd>key=value</kbd>, such as JVM command line system properties.</p>
 *
 * @since 2.4
 * @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
 * @version $Id: KeyValuePair.java,v 1.3 2008/04/01 22:09:41 pholser Exp $
 */
public final class KeyValuePair {
    public final String key;
    public final String value;

    private KeyValuePair( String key, String value ) {
        this.key = key;
        this.value = value;
    }

    /**
     * Parses a string assumed to be of the form <kbd>key=value</kbd> into its parts.
     *
     * @param stringRepresentation key-value string
     * @return a key-value pair
     * @throws NullPointerException if <code>stringRepresentation</code> is
     * <code>null</code>
     */
    public static KeyValuePair valueOf( String stringRepresentation ) {
        int equalsIndex = stringRepresentation.indexOf( '=' );
        if ( equalsIndex == -1 )
            return new KeyValuePair( stringRepresentation, Strings.EMPTY );

        String aKey = stringRepresentation.substring( 0, equalsIndex );
        String aValue;

        if ( equalsIndex == stringRepresentation.length() - 1 )
            aValue = Strings.EMPTY;
        else
            aValue = stringRepresentation.substring( equalsIndex + 1 );

        return new KeyValuePair( aKey, aValue );
    }

    /**
     * {@inheritDoc}
     */
    public boolean equals( Object that ) {
        if ( this == that )
            return true;

        if ( !( that instanceof KeyValuePair ) )
            return false;

        KeyValuePair other = (KeyValuePair) that;
        return key.equals( other.key ) && value.equals( other.value );
    }

    /**
     * {@inheritDoc}
     */
    public int hashCode() {
        return key.hashCode() ^ value.hashCode();
    }

    /**
     * {@inheritDoc}
     */
    public String toString() {
        return key + '=' + value;
    }
}
