//Dieses Skript erstellt eine XML-Datei mit Gruppen-IDs die gelöscht werden sollen. Die XML-Datei kann per d.3 administration importiert werden.
//Ausgeführt wird dieses Skript per d.3 server interface, zuvor muss das SQL-Statement angepasst werden. Das SQL-Statement muss die Gruppen-IDs der zu löschenden Gruppen liefern.

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 javax.swing.*;
String scriptName = getClass().getName()

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog (null, "Dies ist ein nicht supportetes Tool und ist nur fuer den internen Einsatz durch die d.velop AG gedacht.\nEs koennen erhebliche Schaeden in Ihrer d.velop documents Umgebung entstehen.\n \nWollen Sie wirklich fortfahren?\n ---------------------------------------------------\nThis is an unsupported tool and is only intended for internal use by d.velop AG.\nConsiderable damage can occur in your d.velop documents environment.\n \nAre you sure you want to continue?","Warning",dialogButton);
if(dialogResult == JOptionPane.NO_OPTION){
    d3.log.info(scriptName + " - cancel")
    return 0;
}

final def maxRows = 3000

def resultSet = d3.sql.executeAndGet("select gruppen_id from benutzergruppen where benutzergruppe like '%GroupsToBeDeleted%'", maxRows)

if(resultSet.size() == 0){
    d3.log.info (scriptName + " - no result for groups to be deleted")
    JOptionPane.showMessageDialog(null, "No result for groups to be deleted.");
    return 0
}

def now = new Date()
File file = new File("ext_groovy/"+scriptName+"_"+now.format("yyyyMMddHHmmss", TimeZone.getTimeZone('UTC'))+".xml")

//Schreibe Kopf der XML-Datei
file.append('<?xml version="1.0" encoding="utf-8"?>\n')
file.append('<master_data>\n')

for (row in resultSet){
	d3.log.info (scriptName + " - preparing group " + row["gruppen_id"] + " for deletion")
	file.append('  <group id="' + row["gruppen_id"] + '" action="DELETE"/>\n')
}

//Schreibe Fuß der XML-Datei
file.append('</master_data>')

d3.log.info (scriptName + " - Creation of transportfile ("+file+") finished. Please consider that result for groups to be deleted is correct.")
d3.log.info (scriptName + " - If result is correct the transportfile can be imported via d.3 administration.")
JOptionPane.showMessageDialog(null, "Creation of transportfile ("+file+") finished. Please consider that result for groups to be deleted is correct.\n If result is correct the transportfile can be imported via d.3 administration.");