package com.agilex.healthcare.schedulingmanager.mdws;

import com.agilex.healthcare.utility.DateHelper;

import java.util.Date;

public class MdwsDateTranslationUtil {
	
	private static String VA_DEFAULT_START_DATE_CDW_FORMAT = "01/01/1990";
	private static String VA_DEFAULT_START_DATE_VISTA_FORMAT = "19900101.000000";

	public static String dateFormatBySystem(Date date, String system) {
		if (system.equalsIgnoreCase(MdwsDataSourceCode.VISTA))
			return DateHelper.formatDateTimeInVistaFormat(date);

		return DateHelper.formatDate(date);
	}

	public static Date extractDateOrNull(String date) {
		Date parsedDate = parseVistaDateTime(date);
		if(parsedDate == null)
			parsedDate = parseVistaDate(date);
		if(parsedDate == null)
			parsedDate = parseCdwDateTime(date);
		if (parsedDate == null)
			parsedDate = parseCdwDate(date);
		
		return parsedDate;
	}

	public static String startDateBySystem(Date date, String system) {
		if(MdwsDataSourceCode.VISTA.equalsIgnoreCase(system)) 
			return startDateInVistaFormat(date);
	
		return startDateInCdwFormat(date);
	}
	 
	public static String endDateBySystem(Date date, String system) {
		if(MdwsDataSourceCode.VISTA.equalsIgnoreCase(system))
			return endDateInVistaFormat(date);
		
		return endDateInCdwFormat(date);
	}
	
	public static String startDateInCdwFormat(Date date) {
		if(date == null)
			return VA_DEFAULT_START_DATE_CDW_FORMAT;
		
		return DateHelper.formatDate(date);
	}
	
	public static String startDateInVistaFormat(Date date) {
		if(date == null) 
			return VA_DEFAULT_START_DATE_VISTA_FORMAT;
		
		return DateHelper.formatDateTimeInVistaFormat(date);
	}
	
	public static String endDateInCdwFormat(Date date) {
		if(date == null)
			date = new Date();
		
		return DateHelper.formatDate(date);
	}
	
	public static String endDateInVistaFormat(Date date) {
		if(date == null)
			date = new Date();
		
		return DateHelper.formatDateTimeInVistaFormat(date);
	}

	private static Date parseVistaDate(String date) {
		try {
			return DateHelper.parseVistaDate(date);
		} catch (RuntimeException e) {
			// If we can't parse this format, return null
		}

		return null;
	}
	
	private static Date parseVistaDateTime(String date) {
		try {
			return DateHelper.parseVistaDateTimeOrNull(date);
		} catch (RuntimeException e) {
			// If we can't parse this format, return null
		}
		
		return null;
	}

	private static Date parseCdwDateTime(String date) {
		try {
			return DateHelper.parseDateTime(date);
		} catch (RuntimeException e) {
			// If we can't parse this format, return null
		}

		return null;
	}
	
	private static Date parseCdwDate(String date) {
		try {
			return DateHelper.parseDate(date);
		} catch (RuntimeException e) {
		}

		return null;
	}
}
