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

package com.basilv.resumecalculator;

import java.io.*;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.joda.time.Duration;

import com.basilv.core.Assert;

/**
 * Service for performing resume calculations for the application.
 */
public class ResumeCalculatorService
{
	public static interface CalculateDurationReporter {
		public void handleExceptionParsingResumeFile(File resumeFile, Exception e);
		
		public void reportCalculatedDurationInMonthsAndYears(double months, double years);
		
		public void reportSettings(Resume resume, List<String> entryIds);
	}
	
	public boolean calculateDurationOfEntries(Settings settings, CalculateDurationReporter reporter) {
		Assert.notNull("settings", settings);
		Assert.notNull("reporter", reporter);
		
		File resumeFile = settings.getResumeFile(); 
		Assert.notNull("resumeFile", resumeFile);
		
		Assert.notNull("resumeEntryIds", settings.getEntryIds());

		Resume resume = null;
		
		try {
			Reader resumeReader = new BufferedReader(new FileReader(resumeFile));
			
			try {
				resume = XmlBindingTools.parseXML(resumeReader, Resume.class);
			} catch (JAXBException e) {
				reporter.handleExceptionParsingResumeFile(resumeFile, e);
				return false;
			} finally {
				resumeReader.close();
			}
		} catch (IOException e) {
			reporter.handleExceptionParsingResumeFile(resumeFile, e);
			return false;
		}

		reporter.reportSettings(resume, settings.getEntryIds());
		
		// Do calculations based on entry list.
		ResumeDurationCalculator calculator = new ResumeDurationCalculator();
		Duration duration = calculator.calculateDurationOfEntriesInResume(resume, settings.getEntryIds());

		double months = DateTimeUtils.convertDurationToMonths(duration);
		double years = DateTimeUtils.convertDurationToYears(duration);
		reporter.reportCalculatedDurationInMonthsAndYears(months, years);
		
		return true;

	}
	
}
