/**
 * Genji Scrum Tool and Issue Tracker
 * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions

 * <a href="http://www.trackplus.com">Genji Scrum Tool</a>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* $Id:$ */

package com.aurel.track.persist;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.torque.TorqueException;
import org.apache.torque.util.Criteria;

import com.aurel.track.beans.TSiteBean;
import com.aurel.track.dao.SiteDAO;

/**
 * The skeleton for this class was autogenerated by Torque on:
 *
 * [Tue Jun 15 21:31:34 CEST 2004]
 *
 *  You should add additional methods to this class to meet the
 *  application requirements.  This class will only be generated as
 *  long as it does not already exist in the output directory.
 */
public class TSitePeer
extends com.aurel.track.persist.BaseTSitePeer implements SiteDAO{

    private static final long serialVersionUID = -130849904047755361L;
    private static final Logger LOGGER = LogManager.getLogger(TSitePeer.class);


    public static TSite load() {
        Criteria crit = new Criteria();
        List siteList = null;
		try {
			siteList = doSelect(crit);
		} catch (TorqueException e) {
			LOGGER.error("Getting the site bean failed with " + e.getMessage());
		}
		if (siteList==null) {
			LOGGER.warn("No site object found");
			return null;
		}
        Iterator i = siteList.iterator();
        TSite site = null;
        if (i.hasNext()) {
            site = (TSite) i.next();
            LOGGER.debug("Could retrieve site configuration");
        }
        return site;
    }

	@Override
	public TSiteBean load1() {
		try {
			TSiteBean site=load().getBean();
			if(site.getMailReceivingProtocol()==null||
					site.getMailReceivingProtocol().length()==0){
				site.setMailReceivingProtocol("pop3");
			}
			return site;
		} catch (Exception e) {
			LOGGER.error("Could retrieve site configuration");
			return null;
		}
	}

	/**
	 * loads, updates and saves the TSiteBean in a synchronized method
	 * @param fieldValues
	 */
	@Override
	synchronized public void loadAndSaveSynchronized(Map<Integer, Object> fieldValues) {
		TSiteBean siteBean = load1();
		if (siteBean==null || fieldValues==null || fieldValues.isEmpty()) {
			return;
		}
		Iterator<Integer> iterator = fieldValues.keySet().iterator();
		while (iterator.hasNext()) {
			Integer columnID = iterator.next();
			Object value = fieldValues.get(columnID);
			switch(columnID) {
			case TSiteBean.COLUMNIDENTIFIERS.TRACKVERSION:
				siteBean.setTrackVersion((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.DBVERSION:
				siteBean.setDbVersion((String)value);
				break;
			/*case TSiteBean.COLUMNIDENTIFIERS.LICENSEKEY:
				siteBean.setLicenseKey((String)value);
				break;*/
			case TSiteBean.COLUMNIDENTIFIERS.EXPDATE:
				siteBean.setExpDate((Date)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.NUMBEROFUSERS:
				siteBean.setNumberOfUsers((Integer)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.TRACKEMAIL:
				siteBean.setTrackEmail((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.SMTPSERVERNAME:
				siteBean.setSmtpServerName((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.SMTPPORT:
				siteBean.setSmtpPort((Integer)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.MAILENCODING:
				siteBean.setMailEncoding((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.SMTPUSER:
				siteBean.setSmtpUser((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.SMTPPASSWORD:
				siteBean.setSmtpPassWord((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.POPSERVERNAME:
				siteBean.setMailReceivingServerName((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.POPPORT:
				siteBean.setMailReceivingPort((Integer)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.POPUSER:
				siteBean.setMailReceivingUser((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.POPPASSWORD:
				siteBean.setMailReceivingPassword((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.ALLOWEDEMAILPATTERN:
				siteBean.setAllowedEmailPattern((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.ISLDAPON:
					siteBean.setIsLDAPOn((String)value);
				break;

			case TSiteBean.COLUMNIDENTIFIERS.LDAPSERVERURL:
				siteBean.setLdapServerURL((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.LDAPATTRIBUTELOGINNAME:
				siteBean.setLdapAttributeLoginName((String)value);
				break;

			case TSiteBean.COLUMNIDENTIFIERS.DESCRIPTIONLENGTH:
				siteBean.setDescriptionLength((Integer)value);
				break;

			case TSiteBean.COLUMNIDENTIFIERS.HISTORYENTITY:
				siteBean.setHistoryEntity((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.HISTORYMIGRATIONID:
				siteBean.setHistoryMigrationID((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.USELUCENE:
				siteBean.setUseLucene((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.INDEXATTACHMENTS:
				siteBean.setIndexAttachments((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.REINDEXONSTARTUP:
				siteBean.setReindexOnStartup((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.ANALYZER:
				siteBean.setAnalyzer((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.LASTSERVERURL:
				siteBean.setLastServerURL((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.LASTBASEURL:
				siteBean.setLastBaseURL((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.DERBY_BACKUP:
				siteBean.setDerbyBackup((String)value);
				break;
			case TSiteBean.COLUMNIDENTIFIERS.INSTDATE:
				siteBean.setDerbyBackup((String)value);

			}
		}
		save(siteBean);
	}

	/**
	 * Sets the SMTPUser and SMTPPassword fields to null
	 *
	 */
	@Override
	public void clearSMTPPassword() {
		TSite site = load();
		site.setSmtpPassWord(null);
		site.save();
	}

	@Override
	public void save(TSiteBean siteBean) {
		try {
			if (siteBean.getExpDate() != null) {
				siteBean.setExpDate(new java.sql.Date(siteBean.getExpDate().getTime()));
			}
			TSite siteTorque=BaseTSite.createTSite(siteBean);
			siteTorque.save();
		} catch (TorqueException e) {
			LOGGER.error("Saving the site bean failed with " + e.getMessage());
		}
	}

	/**
	 *
	 */
	public Double loadPing() {
		try {
			String COUNT = "count(" + BaseTSitePeer.OBJECTID + ")";
			Criteria crit = new Criteria(); // use empty Criteria to get all entries
			crit.addSelectColumn(COUNT);    // SELECT count(OBJECTID);
			Date start = new Date();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			(doSelectVillageRecords(crit).get(0)).getValue(1).asInt();
			Date stop = new Date();
			return  new Double((stop.getTime() - start.getTime()))/10.0;
			// get the one and only returned record. Get the first value in this record.
			// Record values index always starts at 1.
		} catch (Exception e) {

		}
		return new Double(0.0);
	}
}
