package com.eactive.eai.rms.data.entity.onl.server;

import java.util.List;
import java.util.Optional;

import org.hibernate.annotations.QueryHints;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.entity.onl.server.EAIServer;
import com.eactive.eai.data.entity.onl.server.QEAIServer;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.types.dsl.Expressions;

@Service
@Transactional
public class EAIServerService extends AbstractDataService<EAIServer, String, EAIServerEMSRepository> {

	public List<EAIServer> selectEaiServerIpList() {
		QEAIServer qeaiServer = QEAIServer.eAIServer;
		return getJPAQueryFactory()
				.selectFrom(qeaiServer)
				.where(qeaiServer.eaisevrinstncname.ne("ALL"))
				.where(qeaiServer.eaisevrip.ne("*"))
				.orderBy(qeaiServer.eaisevrip.asc(), qeaiServer.sevrlsnportname.asc())
				.setHint(QueryHints.CACHEABLE, true)
				.fetch();
	}

	public EAIServer getByEaiSevrInstncName(String eaiInstanceName) {
		QEAIServer qeaiServer = QEAIServer.eAIServer;
		return getJPAQueryFactory()
				.selectFrom(qeaiServer)
				.where(qeaiServer.eaisevrinstncname.eq(eaiInstanceName))
				.fetchOne();
	}
	
	public Optional<EAIServer> findByEaiSevrInstncName(String eaiInstanceName) {
		try {
			return Optional.of(getByEaiSevrInstncName(eaiInstanceName));
		} catch (RuntimeException e) {
			return Optional.ofNullable(null);
		}
	}

	public List<EAIServer> findAllFailOverServer(String svrInstName) {
		QEAIServer qeaiServer = QEAIServer.eAIServer;
		return getJPAQueryFactory()
				.selectFrom(qeaiServer)
				.where(qeaiServer.eaisevrinstncname.ne("ALL"))
				.where(qeaiServer.eaisevrinstncname.ne(svrInstName))
				.orderBy(qeaiServer.eaisevrinstncname.asc())
				.fetch();
	}

	public int selectTakeOverCount() {
		QEAIServer qeaiServer = QEAIServer.eAIServer;
		return getJPAQueryFactory()
				.selectFrom(qeaiServer)
				.where(qeaiServer.eaisevrinstncname.ne("ALL"))
				.groupBy(Expressions
						.stringTemplate("concat(substr({0}, 1, 9), '_', substr({0}, 11, 1))",
								qeaiServer.eaisevrinstncname))
				.having(qeaiServer.eaisevrinstncname.count().gt(1L))
				.fetch()
				.size();
	}

	public Optional<EAIServer> findFirstByHostname(String searchHostNm) {
		QEAIServer qeaiServer = QEAIServer.eAIServer;
		EAIServer eaiServer = getJPAQueryFactory()
				.selectFrom(qeaiServer)
				.where(qeaiServer.eaisevrinstncname.ne("ALL"))
				.where(qeaiServer.eaisevrip.ne("*"))
				.where(qeaiServer.hostname.eq(searchHostNm))
				.fetchFirst();
		return Optional.of(eaiServer);
	}

}
