package com.eactive.eai.rms.common.acl.audit.adapter.out.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import com.eactive.eai.rms.common.acl.audit.port.in.SelectListAuditLogCommand;
import com.eactive.eai.rms.data.EMSDataSource;
import com.eactive.eai.rms.data.entity.man.audit.AuditLogEntity;
import com.eactive.eai.rms.data.entity.man.audit.QAuditLogEntity;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;

@EMSDataSource
public class AuditLogPageRepositoryImpl implements AuditLogPageRepository {

	private EntityManager entityManager;

	@PersistenceContext(unitName = "entityManagerFactoryForEMS")
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public Page<AuditLogEntity> findPage(Pageable pageable, SelectListAuditLogCommand command) {

		QAuditLogEntity qAuditLogEntity = QAuditLogEntity.auditLogEntity;
		JPAQuery<Long> jpaQuery = new JPAQueryFactory(entityManager)
				.select(qAuditLogEntity.count())
				.from(qAuditLogEntity);

		jpaQuery
				.where(qAuditLogEntity.lastModifiedDate
						.between(command.getSearchStartDateTime(), command.getSearchEndDateTime()));

		if (StringUtils.isNotBlank(command.getSearchSystemCode())) {
			jpaQuery.where(qAuditLogEntity.systemCode.eq(command.getSearchSystemCode()));
		}
		if (StringUtils.isNotBlank(command.getSearchLogTypeText())) {
			jpaQuery.where(qAuditLogEntity.logTypeText.containsIgnoreCase(command.getSearchLogTypeText()));
		}
		if (StringUtils.isNotBlank(command.getSearchUserId())) {
			jpaQuery.where(qAuditLogEntity.userId.containsIgnoreCase(command.getSearchUserId()));
		}
		if (StringUtils.isNotBlank(command.getSearchRemoteAddress())) {
			jpaQuery.where(qAuditLogEntity.remoteAddress.containsIgnoreCase(command.getSearchRemoteAddress()));
		}

		long totalCount = jpaQuery.fetchOne();
		List<AuditLogEntity> auditLogs = jpaQuery
				.select(qAuditLogEntity)
				.offset(pageable.getOffset())
				.limit(pageable.getPageSize())
				.orderBy(qAuditLogEntity.lastModifiedDate.desc())
				.fetch();

		return new PageImpl<>(auditLogs, pageable, totalCount);
	}
}
