/*
 * Ktunaxa Referral Management System.
 *
 * Copyright (C) see version control system
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.ktunaxa.referral.server.service;

import javax.annotation.PostConstruct;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Resets the referral count when the year has passed.
 * 
 * @author Jan De Moerloose
 * 
 */
@Component
public class ResetReferralCounterService implements PreInsertEventListener {

	private final Logger log = LoggerFactory.getLogger(ResetReferralCounterService.class);

	@Autowired
	private SessionFactoryImpl sessionFactoryImpl;

	@PostConstruct
	public void registerListeners() {
		sessionFactoryImpl.getEventListeners().setPreInsertEventListeners(
				new org.hibernate.event.PreInsertEventListener[] { this });
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean onPreInsert(PreInsertEvent event) {
		Session session = sessionFactoryImpl.getCurrentSession();
		SQLQuery q1 = session
				.createSQLQuery(
						"SELECT count(*) as cnt, to_char(current_date, 'yyyy') as yr "
								+ "FROM referral WHERE calendar_year = cast(to_char(current_date, 'yy') as integer)")
				.addScalar("cnt", new IntegerType()).addScalar("yr", new StringType());
		Object[] result = (Object[]) q1.uniqueResult();
		Integer cnt = (Integer) result[0];
		String yr = (String) result[1];
		log.info("Found " + cnt + " referrals for the current year " + yr);
		if (cnt == 0) {
			log.info("No referrals found for the current year " + yr
					+ ", resetting sequence before adding the first referral");
			// resetting this way is not completely safe in the (unlikely) case that multiple referrals are committed
			// concurrently, but we'll live with the intermittent failure
			session.createSQLQuery("setvalue('referral_number_seq',0)");
		}
		return false;
	}

}

@@ -1969,16 +1969,176 @@
 ent) %7B%0D%0A
+%09%09// using the current session causes flush, followed by rg.hibernate.AssertionFailure: null id in%0D%0A%09%09// org.ktunaxa.referral.server.domain.Referral entry ?!!%0D%0A
 %09%09Sessio
@@ -2172,18 +2172,12 @@
 mpl.
-getCurr
+op
 en
-t
 Sess
@@ -2184,16 +2184,26 @@
 ion();%0D%0A
+%09%09try %7B%0D%0A%09
 %09%09SQLQue
@@ -2223,16 +2223,17 @@
 on%0D%0A%09%09%09%09
+%09
 .createS
@@ -2242,16 +2242,17 @@
 Query(%0D%0A
+%09
 %09%09%09%09%09%09%22S
@@ -2313,16 +2313,17 @@
 s yr %22%0D%0A
+%09
 %09%09%09%09%09%09%09%09
@@ -2413,16 +2413,17 @@
 %22)%0D%0A%09%09%09%09
+%09
 .addScal
@@ -2489,16 +2489,17 @@
 ());%0D%0A%09%09
+%09
 Object%5B%5D
@@ -2539,16 +2539,17 @@
 ult();%0D%0A
+%09
 %09%09Intege
@@ -2580,16 +2580,17 @@
 %5B0%5D;%0D%0A%09%09
+%09
 String y
@@ -2614,16 +2614,17 @@
 lt%5B1%5D;%0D%0A
+%09
 %09%09log.in
@@ -2686,16 +2686,17 @@
 + yr);%0D%0A
+%09
 %09%09if (cn
@@ -2705,24 +2705,25 @@
 == 0) %7B%0D%0A%09%09%09
+%09
 log.info(%22No
@@ -2768,16 +2768,17 @@
 %22 + yr%0D%0A
+%09
 %09%09%09%09%09+ %22
@@ -2842,52 +2842,11 @@
 %0A%09%09%09
+%09
 //
- resetting this way is not completely safe
  in 
@@ -2906,15 +2906,8 @@
 tted
-%0D%0A%09%09%09//
  con
@@ -2920,55 +2920,107 @@
 tly,
- but we'll live with the intermittent failure
+%0D%0A%09%09%09%09// this may cause loss of one or more concurrent referrals because of duplicate key errors
 %0D%0A
+%09
 %09%09%09s
@@ -3080,16 +3080,58 @@
 ,0)%22);%0D%0A
+%09%09%09%7D%0D%0A%09%09%7D finally %7B%0D%0A%09%09%09session.close();%0D%0A
 %09%09%7D%0D%0A%09%09r

use new session to avoid flush problem