// Copyright 2008 by Basil Vandegriend.  All rights reserved.

package com.basilv.resumecalculator;

import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


/**
 * Converts local dates to and from strings.
 */
public class XmlResumeEntryIntervalAdapter extends XmlAdapter<XmlResumeEntryIntervalAdapter.StringWrapper, Interval>
{
	private static final DateTimeFormatter monthYearFormatter = DateTimeFormat.forPattern("MMM, YYYY");
	private static final DateTimeFormatter yearFormatter = DateTimeFormat.forPattern("YYYY");

	static class StringWrapper {
		@XmlValue
		public String value;
	}
	
	@Override
	public StringWrapper marshal(Interval interval) {
		StringWrapper stringWrapper = new StringWrapper();
		stringWrapper.value = interval.toString();
		throw new UnsupportedOperationException();
//		return stringWrapper;
	}

	@Override
	public Interval unmarshal(StringWrapper wrapper) throws IllegalArgumentException {
		String value = wrapper.value;
		if (value == null) {
			throw new IllegalArgumentException("Supplied interval is null.");
		}
		String[] dates = splitIntoStartAndEndValues(value);
		String startValue = dates[0].trim();
		String endValue = dates[1].trim();
		
		DateTime startDate = parseStartDate(startValue);
		DateTime endDate = parseEndDate(endValue);
		
		Interval interval = new Interval(startDate, endDate);
		return interval;
	}

	String[] splitIntoStartAndEndValues(String value) {
		String dateSeparatorSymbol = "-";
		int dashIndex = value.indexOf(dateSeparatorSymbol);

		String invalidIntervalMessage = "Invalid interval: Must supply a start and end value separate by a dash '-'.";
		if (dashIndex < 1 || dashIndex == value.length()-1) {
			throw new IllegalArgumentException(invalidIntervalMessage);
		}
		String[] dates = value.split(dateSeparatorSymbol);
		if (dates.length != 2) {
			throw new IllegalArgumentException(invalidIntervalMessage);
		}
		return dates;
	}

	// Non-private for testing
	DateTime parseStartDate(String value) throws IllegalArgumentException {
		if (value == null) {
			throw new IllegalArgumentException("Supplied date is null.");
		}
		DateTimeFormatter formatter = null;
		if (value.contains(",")) {
			formatter = monthYearFormatter;
		} else {
			formatter = yearFormatter;
		}
		DateTime date = formatter.parseDateTime(value);
		return date;
	}
	
	DateTime parseEndDate(String value) throws IllegalArgumentException {
		if ("Present".equalsIgnoreCase(value) ||
			"Current".equalsIgnoreCase(value)) {
			return 	new DateTime();
		}
		// If no special case then same parsing as start date
		return parseStartDate(value);
	}
			
}



