package com.jasamedika.medifirst2000.util;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Calendar;
import java.util.Date;

public final class AgeCalculator {
	public AgeCalculator() {

	}

	public static Age calculateAge(Date birthDate) {
		Age age = null;
		if(CommonUtil.isNotNullOrEmpty(birthDate)) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			LocalDate today = LocalDate.now();
	        LocalDate birthday = LocalDate.parse(format.format(birthDate));
	        Period period = Period.between(birthday, today);
	        if(CommonUtil.isNotNullOrEmpty(period)) {
	        	age = new Age(period.getDays(), period.getMonths(), period.getYears());
	        }
		}
		return age;
	}
	
	public static Age calculateAge2(final Date tglRegistrasi,final Date birthDate) {
		int years = 0;
		int months = 0;
		int days = 0;
		try
		{
			// create calendar object for birth day
			Calendar birthDay = Calendar.getInstance();
			birthDay.setTimeInMillis(birthDate.getTime());
			// create calendar object for current day
//			long currentTime = System.currentTimeMillis();
//			Calendar now = Calendar.getInstance();
//			now.setTimeInMillis(currentTime);
			Calendar regDay = Calendar.getInstance();
			regDay.setTimeInMillis(tglRegistrasi.getTime());
			// Get difference between years
			years = regDay.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
			int currMonth = regDay.get(Calendar.MONTH) + 1;
			int birthMonth = birthDay.get(Calendar.MONTH) + 1;
			// Get difference between months
			months = currMonth - birthMonth;
			// if month difference is in negative then reduce years by one and
			// calculate the number of months.
			if (months < 0) {
				years--;
				months = 12 - birthMonth + currMonth;
				if (regDay.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
					months--;
			} else if (months == 0
					&& regDay.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
				years--;
				months = 11;
			}
			// Calculate the days
			if (regDay.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
				days = regDay.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
			else if (regDay.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
				int today = regDay.get(Calendar.DAY_OF_MONTH);
				regDay.add(Calendar.MONTH, -1);
				days = regDay.getActualMaximum(Calendar.DAY_OF_MONTH)
						- birthDay.get(Calendar.DAY_OF_MONTH) + today;
			} else {
				days = 0;
				if (months == 12) {
					years++;
					months = 0;
				}
			}
		}
		catch(Exception ex)
		{
			
		}
		
		// Create new Age object
		return new Age(days, months, years);
	}
}

