/*
 * $Id$
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log$
 * Revision 1.4  2007/11/05 08:53:41  marbobo
 * + Bugfix (Statt List werden HashSet benutzt)
 *
 * Revision 1.3  2007/01/12 12:58:24  korowa
 * bugfixing: Die leere Liste mit dynamischen attributen wird jetzt auch gespeichert
 *
 * Revision 1.2  2006/09/10 20:46:56  marbobo
 * + Bugfix
 *
 * Revision 1.1  2006/08/31 12:23:26  korowa
 * Dynamische Attribute für Users eingefügt
 *
 *
 */
package vkc.db.serializer;

import java.sql.Connection;

import vkc.db.entities.VKCDynUserAttribute;
import vkc.db.helper.DBHelper;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.view.WebShare;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

public class VKCDynUserAttributeSerializer {
    private VKCDynUserAttributeSerializer() {
    }

    /**
     * Speichert alle verfügbaren Attribute für einen User.
     * 
     * @param conn
     *            Die Connection
     * @param Liste
     *            der VKCDynUserAttribute des Users
     * @throws HibernateException
     * @throws SQLException
     */

    public static final void saveDynUserAttributes(Connection conn, List dynaAttributes, Integer userId) {
        // Methodenweite Variablen
        PreparedStatement pStmt1 = null;
        PreparedStatement pStmt2 = null;
        String sqlStmt = null;

        try {
            if (dynaAttributes != null) {
                // zunächst alle Einträge löschen ...
                sqlStmt = "DELETE FROM " + "dynuserattrvalues" + " WHERE " + "userId" + " = ?";
                pStmt1 = conn.prepareStatement(sqlStmt);
                pStmt1.setInt(1, userId.intValue());
                pStmt1.execute();

                // ... dann alle neuen Einträge schreiben
                sqlStmt = "INSERT INTO dynuserattrvalues (userId, userattrid, name, valuestring, autorization) VALUES (?, ?, ?, ?, ?)";
                pStmt2 = conn.prepareStatement(sqlStmt);

                if (dynaAttributes.size() > 0) {
                    for (int i = 0; i < dynaAttributes.size(); i++) {
                        VKCDynUserAttribute addAttr = (VKCDynUserAttribute) dynaAttributes.get(i);
                        addAttr.setDynaAttrId(DBHelper.getNewId(conn, "dynuserattrvalues", "userattrid"));
                        pStmt2.setInt(1, userId.intValue());
                        pStmt2.setInt(2, addAttr.getDynaAttrId().intValue());
                        pStmt2.setString(3, addAttr.getName());
                        pStmt2.setString(4, addAttr.getValue());
                        pStmt2.setInt(5, addAttr.getAutorization().intValue());
                        pStmt2.execute();
                    }
                }
            }
        } catch (Exception ex) {
            VKCLogManager.errorLog(VKCAddAttributeSerializer.class, "1", "Error occured while save additional attributes!", ex);
        } finally {
            DBHelper.close(pStmt1);
            DBHelper.close(pStmt2);
        }
    }

    /**
     * Lädt dynamische Attribute eines VKCUsers aus der Datenbank
     * 
     * @param userId
     *            ID VKCUsers, deren Attribute geladen werden sollen
     * @return Liste der VKCDynUserAttribute des Users
     */
    public static final Vector retrieveDynUserAttributes(Integer userId) throws DBException {
        if (userId == null) {
            return null;
        }

        Connection conn = null;

        try {
            conn = WebShare.database.getConnection();

            return retrieveDynUserAttributes(conn, userId);
        } catch (Exception e) {
            throw new DBException(e);
        } finally {
            DBHelper.close(conn);
        }
    }

    /**
     * Lädt alle verfügbaren Attribute einen User.
     * 
     * @param conn
     *            Die Connection
     * @param userId
     *            Id einen User dessen Attribute geholt werden sollen
     * @return Vector mit VKCDynUserAttribute Objekten
     * @throws HibernateException
     * @throws SQLException
     */
    private static final Vector retrieveDynUserAttributes(Connection conn, Integer userId) throws SQLException {
        // Methodenweite Variablen
        PreparedStatement pStmt = null;
        ResultSet rs = null;

        try {
            pStmt = conn.prepareStatement("SELECT * FROM DYNUSERATTRVALUES WHERE USERID = ?");
            pStmt.setInt(1, userId.intValue());
            rs = pStmt.executeQuery();

            Vector addEntityAttrs = new Vector();
            while (rs.next()) {
                VKCDynUserAttribute attr = new VKCDynUserAttribute();
                attr.setDynaAttrId(new Integer(rs.getInt("userattrid")));
                attr.setName(rs.getString("name"));
                attr.setValue(rs.getString("valuestring"));
                attr.setAutorization(new Integer(rs.getInt("autorization")));
                attr.setUserId(userId);
                addEntityAttrs.add(attr);
            }

            return addEntityAttrs;
        } finally {
            DBHelper.close(rs);
            DBHelper.close(pStmt);
        }
    }

    /**
     * Speichert dynamische Attribute eines VKCUsers in die Datenbank
     * 
     * @param Liste
     *            der VKCDynUserAttribute des Users
     */
    public static void saveDynUserAttributes(List dynaAttributes, Integer userId) throws DBException {
        if (dynaAttributes == null) {
            return;
        }

        Connection conn = null;

        try {
            conn = WebShare.database.getConnection();
            saveDynUserAttributes(conn, dynaAttributes, userId);
            conn.commit();
        } catch (Exception e) {
            DBHelper.rollBack(conn);
            VKCLogManager.errorLog(VKCUserSerializer.class, "1", "Error saving user: " + dynaAttributes, e);
            throw new DBException(e);
        } finally {
            DBHelper.close(conn);
        }
    }
}