import com.dvelop.d3.server.Document
import com.dvelop.d3.server.core.D3Interface
import com.dvelop.d3.server.exceptions.SQLException
import com.dvelop.d3.server.exceptions.D3Exception
import groovy.transform.Field



D3Interface d3 = getProperty("d3");

@Field prg              = "enervie_akten_anlegen.groovy";
@Field version          = "0.1";
@Field kunde            = "Enervie";

/////////////////////////////////////////////////////////////////////////


// debug = 0 => es finden Änderungen am Datenbestand statt
// debug = 1 => es finden keine Änderungen am Datenbestand statt
@Field debug = 1;






/////////////////////////////////////////////////////////////////////////

def debugtext;

switch (debug)
{
        case 0:
                debugtext = "ausgeschaltet";
                break;
        default:
                debugtext = "eingeschaltet (keine Aenderungen am Datenbestand)";
                break;
}



xlog( d3, 4, "************************************************" );
xlog( d3, 4, "* Programm         : " + prg );
xlog( d3, 4, "* Version          : " + version );
xlog( d3, 4, "* Kunde            : " + kunde );
xlog( d3, 4, "* geschrieben von  : calb / d.velop AG" );
xlog( d3, 4, "* (c) d.velop AG" );
xlog( d3, 4, "************************************************" );


xlog( d3, 4, "Parameter: " );
xlog( d3, 4, "* DEBUG              : " + debugtext );




xlog( d3, 4, "************************************************" );



def file = new File( "D:\\Einspeiseakte\\EEG_Liste2.csv" );

def lines = file.readLines( "UTF-8" );

def headers = parseCsvLine( lines[ 0 ] );
def dataRows = lines[1..33];
def i = 1;
def fehler = false;
Number laenge = 35;

dataRows.eachWithIndex{ line, index ->

	def values = parseCsvLine( line );
	
	def rowMap = [headers, values].transpose().collectEntries { it }
	
	Document newDoc = d3.archive.newDocument();
	
	newDoc.type = "AEINA";
	
	newDoc.status = Document.DocStatus.DOC_STAT_RELEASE;
	
	rowMap.each{ key, value ->
	
		//println "${key}: ${value}"
	
		
		
		
		
		if ( key == "GP-Anrede" )
		{
			newDoc.field[ 22 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF22" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "Anlage Strasse" )
		{
			newDoc.field[ 2 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF2 " + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "Anlage Hausnummer" )
		{
			newDoc.field[ 43 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF43" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "Anlage PLZ" )
		{
			newDoc.field[ 46 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF46" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "Anlage Ort" )
		{
			newDoc.field[ 3 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF3 " + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "Anlage Gesamtwirkleistung" )
		{
			newDoc.field[ 19 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF19" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "Anlage Inbetriebnahme-Datum" )
		{
			def datum_inb = new Date( ).parse( "dd.MM.yyyy", value );
			newDoc.field[ 58 ] = datum_inb;
			xlog( d3, 4, "Nr. " + i + ": DDF58" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "MaStR-Nummer der EEG-/KWK-Anlage" )
		{
			newDoc.field[ 28 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF28" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "MaStR-Nummer der Einheit" )
		{
			newDoc.field[ 27 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF27" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "GP-Strasse" )
		{
			newDoc.field[ 8 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF8 " + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "GP-Hausnummer" )
		{
			newDoc.field[ 44 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF44" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "GP-PLZ" )
		{
			newDoc.field[ 45 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF45" + key.padLeft( laenge ) + " => ${value} " );
		}
		
		if ( key == "GP-Ort" )
		{
			newDoc.field[ 9 ] = value;
			xlog( d3, 4, "Nr. " + i + ": DDF9 " + key.padLeft( laenge ) + " => ${value} " );
		}
		
		
		
		
		
		
	}
	
	
	fehler = false;
	
	if ( debug == 0 )
	{
		try
		{
			newDoc = d3.archive.importDocument( newDoc );
		}
		catch ( D3Exception e )
		{
			fehler = true;
			xlog( d3, 2, "Nr. " + i + ": Akte konnte nicht erzeugt werden: " + e.message );
		}
		
		if ( fehler == false )
		{
			xlog( d3, 4, "Nr. " + i + ": Akte wurde erzeugt, Doku-ID: " + newDoc.id() );
		}
	}
	else
	{
		xlog( d3, 4, "Nr. " + i + ": Akte wurde nicht erzeugt: DEBUG-Modus eingeschaltet." );
	}
	
	
	
	i++;
	xlog( d3, 4, "************************************************" );
	
}






















def xlog( D3Interface d3, int loglevel, String logtext )
{
        def logdatei            = "d:\\d3\\logs\\" + prg + ".txt";
        def g_loglevel          = 5;
        def g_logdirect         = "BEIDE";  // BEIDE oder D3LOG oder DATEI
        def date                = new Date();
        def zeitstempel         = date.format( "yyyy.MM.dd HH:mm:ss", TimeZone.getTimeZone('CET') );
        def loglevel_lang       = "[INFO ]";
        
        
        
        
        
        if ( loglevel <= g_loglevel )
        {
                switch ( loglevel )
                {
                        case 1:
                                loglevel_lang   = "[FATAL]";
                                
                                if ( ( g_logdirect == "D3LOG" ) || ( g_logdirect == "BEIDE" ) )
                                {
                                        d3.log.critical( logtext );
                                }
                                break;
                        case 2:
                                loglevel_lang   = "[ERROR]";
                                
                                if ( ( g_logdirect == "D3LOG" ) || ( g_logdirect == "BEIDE" ) )
                                {
                                        d3.log.error( logtext );
                                }
                                break;
                        case 3:
                                loglevel_lang   = "[WARN ]";
                                
                                if ( ( g_logdirect == "D3LOG" ) || ( g_logdirect == "BEIDE" ) )
                                {
                                        d3.log.warn( logtext );
                                }
                                break;
                        case 4:
                                loglevel_lang   = "[INFO ]";
                                
                                if ( ( g_logdirect == "D3LOG" ) || ( g_logdirect == "BEIDE" ) )
                                {
                                        d3.log.info( logtext );
                                }
                                break;
                        case 5:
                                loglevel_lang   = "[DEBUG]";
                                // Da die d.3 Server i.d.R. nicht im Debug-Modus laufen, erscheinen DEBUG-Meldungen nicht im Log.
                                if ( ( g_logdirect == "D3LOG" ) || ( g_logdirect == "BEIDE" ) )
                                {
                                        d3.log.debug( logtext );
                                }
                                break;
                }
                
        }
        
        if ( ( g_logdirect == "DATEI" ) || ( g_logdirect == "BEIDE" ) )
        {
                new File( logdatei ).append( zeitstempel + " " + loglevel_lang + " " + logtext + "\n", "UTF8" );
        }
        
        
        return 0;
}

def parseCsvLine(String line) {
    def result = []
    def current = ''
    def inQuotes = false
    def i = 0

    while (i < line.length()) {
        def c = line[i]
        if (c == '"') {
            inQuotes = !inQuotes
        } else if (c == ';' && !inQuotes) {
            result << current.trim()
            current = ''
        } else {
            current += c
        }
        i++
    }
    result << current.trim()
    return result.collect { it.replaceAll(/^"|"$/, '') } // entfernt führende/trailing Quotes
}






