package it.integry.integrywmsnative.core.utility;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by GiuseppeS on 07/03/2018.
 */

public class UtilityDate {

    public static class COMMONS_DATE_FORMATS {
        public static final String DMY_SLASH = "dd/MM/yyyy";
        public static final String YMD_SLASH = "yyyy/MM/dd";
        public static final String DMY_TIME_SLASH = DMY_SLASH + " hh:mm";
        public static final String YMD_TIME_SLASH = YMD_SLASH + " hh:mm";


        public static final String DMY_HUMAN = "dd MMM yyyy";
        public static final String DMY_HUMAN_LONG = "dd MMMM yyyy";
    }

    public static Date recognizeDate(String dateString) throws Exception{

        if (dateString == null) {
            return null;
        }

        //SE SONO PIU' DI 10 caratteri allora c'è anche l'ora

        SimpleDateFormat format = null;
        char dateSeparator;

        String onlyDateSubstring = dateString.substring(0, 10);
        if(onlyDateSubstring.contains("/")) dateSeparator = '/';
        else if(onlyDateSubstring.contains("-")) dateSeparator = '-';
        else if(onlyDateSubstring.contains(".")) dateSeparator = '.';
        else throw new Exception("Data non riconosciuta (" + dateString + ")");

        String dateFormatString = (dateString.charAt(2) == dateSeparator)
                ? "dd" + dateSeparator + "MM" + dateSeparator + "yyyy"
                : "yyyy" + dateSeparator + "MM" + dateSeparator + "dd";


        if(dateString.length() > 10){

            char timeSeparator;

            String onlyTimeSubstring = dateString.substring(10, 14);
            if(onlyTimeSubstring.contains("-")) timeSeparator = '-';
            else if(onlyTimeSubstring.contains(":")) timeSeparator = ':';
            else throw new Exception("Time non riconosciuto (" + dateString + ")");

            String timeFormatString = "HH" + timeSeparator + "mm" + timeSeparator + "ss";

            format = new SimpleDateFormat(dateFormatString + " " + timeFormatString);


        } else {
            format = new SimpleDateFormat(dateFormatString);
        }

        return format.parse(dateString);
    }


    public static String formatDate(Date dateToFormat, String format) {
        return new SimpleDateFormat(format).format(dateToFormat);
    }
}
