package org.ros.chatto.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.hibernate.Session;
import org.ros.chatto.config.DBInitializerConfig;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@RequiredArgsConstructor
public class DBInitializerService {

	private final DBInitializerConfig dbInitializerConfig;

	@PersistenceContext
	private EntityManager entityManager;

	@EventListener(ApplicationReadyEvent.class)
	@Transactional
	public void doSomethingAfterStartup() throws SQLException, IOException {
		log.info("Application Started - running initializer service");

		final Session session = entityManager.unwrap(Session.class);

		session.doWork(connection -> {
			log.info("Clearing tokens");
			clearAllTokens(connection);
		});

		session.doWork(connection -> {
			log.info("Resetting all user sessions");
			resetAllUserSessions(connection);
		});
	}

	private void resetAllUserSessions(final Connection connection) throws SQLException {
		final PreparedStatement preparedStatement = connection
				.prepareStatement(dbInitializerConfig.getResetSessionsQuery());
		preparedStatement.executeUpdate();
	}

	private void clearAllTokens(final Connection connection) throws SQLException {
		final PreparedStatement preparedStatement = connection
				.prepareStatement(dbInitializerConfig.getClearTokensQuery());
		preparedStatement.executeUpdate();
	}

}