/* ************************************************************************
#
#  DivConq
#
#  http://divconq.com/
#
#  Copyright:
#    Copyright 2012 eTimeline, LLC. All rights reserved.
#
#  License:
#    See the license.txt file in the project's top-level directory for details.
#
#  Authors:
#    * Andy White
#
************************************************************************ */
package divconq.struct.scalar;

import divconq.struct.ScalarStruct;
import divconq.struct.Struct;
import divconq.util.StringUtil;

public class StringStruct extends ScalarStruct {
	protected String value = null;
	
	@Override
	public Object getGenericValue() {
		return this.value;
	}
	
	@Override
	public void adaptValue(Object v) {
		this.value = Struct.objectToString(v);
	}

	public String getValue() {
		return this.value; 
	}
	
	public void setValue(String v) { 
		this.value = v; 
	}

	public StringStruct() {		
	}

	public StringStruct(String value) {		
		this.value = value; 
	}
	
	@Override
	public boolean isEmpty() {
		return StringUtil.isEmpty(this.value);
	}
	
		/*
			// TODO also implement
			// <Piece Delim="str" Index="num" />
			// <LeftPad Size="num" Char="c" />
			// <RightPad Size="num" Char="c" />
			// <FitTo Size="num" Pad="left|right" PadChar="c" />

			switch (operation)
			{
				case "TrimEnd":
					Value = iv.Value.TrimEnd();
					break;
				case "TrimStart":
					Value = iv.Value.TrimStart();
					break;
			}
		*/

	@Override
	public Object clone() {
		StringStruct n = new StringStruct();
		//n.setName(this.name);
		n.setValue(this.value);
		return n;
	}

	@Override
	public boolean equals(Object obj) {
		return (StringStruct.comparison(this, obj) == 0);
	}

	@Override
	public int compare(Object y) {
		return StringStruct.comparison(this, y);
	}

	@Override
	public int hashCode() {
		return (this.value == null) ? 0 : this.value.hashCode();
	}
	
	@Override
	public String toString() {
		return (this.value == null) ? "null" : this.value.toString();
	}

	public static int comparison(Object x, Object y)
	{
		if ((y == null) && (x == null))
			return 0;

		if (y == null)
			return 1;

		if (x == null)
			return -1;

		if ((x instanceof StringStruct) && (y instanceof StringStruct)) {
			String xv = ((StringStruct)x).getValue();
			String yv = ((StringStruct)y).getValue();

			if ((yv == null) && (xv == null))
				return 0;

			if (yv == null)
				return 1;

			if (xv == null)
				return -1;

			return xv.compareTo(yv);
		}
		
		// TODO add support for other types

		return 0;
	}
}
