import groovy.time.TimeCategory;
import java.text.DecimalFormat
import java.text.SimpleDateFormat;

abstract class Templates extends Script {

    def formatDateStd = "dd.MM.yyyy";
    def formatDateTimeStd = "dd.MM.yyyy hh:mm:ss";
    
    def now() {
		return new Date();
	}

    def jetzt(f=formatDateTimeStd) {
		return format(now(), f);
	}

    def heute(f=formatDateStd) {
		return format(now(), f);
	}
	
    def ersterTagImMonat(String format=formatDateStd){ 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(new Date()); 
        cal.set(Calendar.DAY_OF_MONTH, 01); 
        return cal.getTime().format(format); 
    } 

    def ersterTagNaechsterMonat(String format=formatDateStd){ 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(new Date()); 
        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 01);  
        return cal.getTime().format(format); 
    }
	
    def letzterTagImMonat(String format=formatDateStd){ 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(new Date()); 
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); 
        return cal.getTime().format(format); 
    }

    def heuteMinusJahre(String format=formatDateStd, int year){ 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(new Date()); 
        cal.add(Calendar.YEAR, -year);
        return cal.getTime().format(format); 
    } 

    def heutePlusJahre(String format=formatDateStd, int year){ 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(new Date()); 
        cal.add(Calendar.YEAR, year);
        return cal.getTime().format(format); 
    } 
	
    def format(date, format=formatDateTimeStd) {
		return date.format(format);
	}	
	
    def NUMBER_OF_CHARS = 5
    def CHARS = ('0'..'9') +
          ('a'..'h') +
          ('j'..'k') +
          ('m'..'z') +
          ('A'..'H') +
          ('J'..'K') +
          ('M'..'Z')

    def random = new Random()

    def uid() {
		def id = ""
		for ( i in 1..NUMBER_OF_CHARS ) {
		  id += CHARS[random.nextInt(CHARS.size())]
		}
		return id
	  }
	  
    def datum = { dateExpr -> 
		def matcher = dateExpr =~ /^(.+?)\.(.+?)\.(.+?)$/
		dExpr = matcher[0][1];
		mExpr = matcher[0][2];
		yExpr = matcher[0][3];

                vdef units = ['DD': Calendar.DAY_OF_MONTH, 'MM': Calendar.MONTH, 'YYYY': Calendar.YEAR] 
                vdef evalExpr = { expr ->
			if(expr.isNumber()) {
				return expr.toInteger();
			} else {
				def additionMatcher = expr =~ /^(.+?)([\+-].+?)$/
				def addition = "+0" 
				def unit = expr;
				if(additionMatcher) {
					addition = additionMatcher[0][2];
					unit = additionMatcher[0][1];       
				}
				return Eval.me(new java.util.Date().getAt(units[unit])+addition);
			}
		}

		def cal = Calendar.getInstance();
		cal.set(evalExpr(yExpr),evalExpr(mExpr),evalExpr(dExpr));
		return cal.getTime().format('dd.MM.yyyy');
	}

}
