package com.eactive.eai.rms.data.entity.man.user;

import java.time.LocalDateTime;
import java.util.List;

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 org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.converter.LocalDateTimeFormatters;
import com.eactive.eai.rms.common.acl.user.ui.UserLoginHistoryUI;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.BooleanBuilder;
import com.eactive.apim.portal.user.entity.QUserInfo;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class UserLoginHistoryService extends AbstractEMSDataSerivce<UserLoginHistory, Integer, UserLoginHistoryRepository>  {

	final String START_HHmmss = " 00:00:00";
	final String END_HHmmss = " 23:59:59";
	
	public Page<UserLoginHistory> findAll(Pageable pageable, UserLoginHistoryUI userLoginHistoryUI) {
		QUserLoginHistory qUserLoginHistory = QUserLoginHistory.userLoginHistory;
		QUserInfo qUserInfo = QUserInfo.userInfo;
		
		BooleanBuilder predicate = new BooleanBuilder();
		
		if(StringUtils.isNotBlank(userLoginHistoryUI.getSearchUserId())) {
			predicate = predicate.and(qUserLoginHistory.userId.containsIgnoreCase(userLoginHistoryUI.getSearchUserId()));
		}
		
		if(StringUtils.isNotBlank(userLoginHistoryUI.getSearchUserName())) {
			predicate = predicate.and(qUserInfo.username.containsIgnoreCase(userLoginHistoryUI.getSearchUserName()));

		}
		
		if(StringUtils.isNotBlank(userLoginHistoryUI.getSearchStartDate())
			 && StringUtils.isNotBlank(userLoginHistoryUI.getSearchEndDate())) {
			
			String startDateStr = userLoginHistoryUI.getSearchStartYYYYMMDD() + START_HHmmss;
			String endDateStr = userLoginHistoryUI.getSearchEndYYYYMMDD() + END_HHmmss;
					
			LocalDateTime startDate = LocalDateTime.parse(startDateStr, LocalDateTimeFormatters.FORMATTER_YYYY_MM_DD_HH_MM_SS_19);
			LocalDateTime endDate = LocalDateTime.parse(endDateStr, LocalDateTimeFormatters.FORMATTER_YYYY_MM_DD_HH_MM_SS_19);
			
			predicate = predicate.and(qUserLoginHistory.loginDttm.between(startDate, endDate));
		}
		
		List<UserLoginHistory> content = getJPAQueryFactory()
				.selectFrom(qUserLoginHistory)
				.join(qUserInfo).on(qUserLoginHistory.userId.eq(qUserInfo.userid))
				.where(predicate)
				.orderBy(qUserLoginHistory.loginLogId.desc())
				.offset(pageable.getOffset())
				.limit(pageable.getPageSize())
				.fetch();
		
		long total = getJPAQueryFactory()
				.select(qUserLoginHistory.countDistinct())
				.from(qUserLoginHistory)
				.where(predicate)
				.join(qUserInfo).on(qUserLoginHistory.userId.eq(qUserInfo.userid))
				.fetchOne();
		
		return new PageImpl<>(content, pageable, total);
	}

}
