package com.eactive.eai.rms.data.entity.onl.apim.portaluserterms;

import com.eactive.apim.portal.portaluser.entity.PortalUserPrivacyAgreement;
import com.eactive.apim.portal.portaluser.entity.QPortalUser;
import com.eactive.apim.portal.portaluser.entity.QPortalUserPrivacyAgreement;
import com.eactive.apim.portal.portaluser.repository.PortalUserPrivacyAgreementRepository;
import com.eactive.eai.rms.common.util.StringUtils;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalUserTermsService extends AbstractEMSDataSerivce<PortalUserPrivacyAgreement, Long, PortalUserPrivacyAgreementRepository> {

	private void addUserSearchCondition(BooleanBuilder predicate, QPortalUserPrivacyAgreement qPortalUserPrivacyAgreement,
										String searchValue, StringPath userField) {

		if (StringUtils.isNotBlank(searchValue)) {
			predicate.and(qPortalUserPrivacyAgreement.createdBy.in(
					getJPAQueryFactory()
							.select(QPortalUser.portalUser.id)
							.from(QPortalUser.portalUser)
							.where(userField.containsIgnoreCase(searchValue))
			));
		}
	}

    public Page<PortalUserPrivacyAgreement> findAll(Pageable pageable, PortalUserTermsSearch search) {
		QPortalUserPrivacyAgreement qPortalUserPrivacyAgreement = QPortalUserPrivacyAgreement.portalUserPrivacyAgreement;
		QPortalUser qPortalUser = QPortalUser.portalUser;

		BooleanBuilder predicate = new BooleanBuilder();

		addUserSearchCondition(predicate, qPortalUserPrivacyAgreement, search.getSearchLoginId(), qPortalUser.loginId);
		addUserSearchCondition(predicate, qPortalUserPrivacyAgreement, search.getSearchUserName(), qPortalUser.userName);

		if (StringUtils.isNotBlank(search.getSearchTermsType())) {
			predicate.and(qPortalUserPrivacyAgreement.termsType.equalsIgnoreCase(search.getSearchTermsType()) );
		}

		if (StringUtils.isNotBlank(search.getSearchAgreementVersion())) {
			predicate.and(qPortalUserPrivacyAgreement.termsVersion.eq(Integer.valueOf(search.getSearchAgreementVersion())) );
		}

		return repository.findAll(predicate, pageable);
	}

	public List<PortalUserPrivacyAgreement> findAllByCreatedBy(String id) {
		QPortalUserPrivacyAgreement qPortalUserPrivacyAgreement = QPortalUserPrivacyAgreement.portalUserPrivacyAgreement;

		return getJPAQueryFactory()
				.selectFrom(qPortalUserPrivacyAgreement)
				.where(qPortalUserPrivacyAgreement.createdBy.eq(id))
				.fetch();
	}
}