/*
 * $Id: VKCTemplateSerializer.java,v 1.6 2006/03/27 22:08:16 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: VKCTemplateSerializer.java,v $
 * Revision 1.6  2006/03/27 22:08:16  marbobo
 * + Bugfixes und Refactoring
 *
 * Revision 1.5  2004/12/05 22:57:47  marbobo
 * + Statement auf PreparedStatement umgestellt
 *
 * Revision 1.4  2004/11/24 09:25:55  lawern
 * Hibernate ist VKC-Geschichte!
 *
 * Revision 1.3  2004/11/18 19:38:23  marbobo
 * + changed order of close-stmt to resultset/connect/session  in finally-blocks
 *
 * Revision 1.2  2004/07/20 08:23:22  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.db.serializer;

import java.sql.Connection;
import vkc.db.entities.VKCTemplate;
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.HashSet;
import java.util.Iterator;
import java.util.Set;

public class VKCTemplateSerializer {
	// cache with installed templates
	private static HashSet templates = new HashSet();

	private VKCTemplateSerializer() {
	}

	public final static Set getTemplates() {
		return templates;
	}

	public final static VKCTemplate getTemplateById(Integer id) {
		if (id == null) {
			return null;
		}

		for (Iterator iter = templates.iterator(); iter.hasNext();) {
			VKCTemplate t = (VKCTemplate) iter.next();

			if (t.getTemplateId().intValue() == id.intValue()) {
				return t;
			}
		}

		return null;
	}

	/**
	 * Liefert alle Templates als HashMap
	 *
	 * @return HashMap mit VKCTemplates und Template-ID als Schlüssel
	 */
	public final static void initTemplates() throws DBException {
		Connection conn = null;
		PreparedStatement pStmt = null;
		ResultSet rs = null;

		try {
			templates.clear();
			conn = WebShare.database.getConnection();
			pStmt = conn.prepareStatement("SELECT * FROM templates");
			rs = pStmt.executeQuery();

			while (rs.next()) {
				VKCTemplate t = new VKCTemplate();
				setFields(t, rs);
				templates.add(t);
			}

		} catch (Exception ex) {
			VKCLogManager.errorLog(VKCTemplateSerializer.class, "1", "Error getting TemplatePath", ex);
			throw new DBException(ex);
		} finally {
			DBHelper.close(rs);
			DBHelper.close(pStmt);
			DBHelper.close(conn);
		}
	}

	private static final void setFields(VKCTemplate t, ResultSet rs) throws SQLException {
		t.setTemplateId(new Integer(rs.getInt("TEMPLATEID")));
		t.setName(rs.getString("name"));
		t.setDescription(rs.getString("description"));
		t.setPreviewPicture(rs.getString("previewpic"));
		t.setPath(rs.getString("path"));
	}
}