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

import com.eactive.apim.portal.template.entity.MessageTemplate;
import com.eactive.apim.portal.template.entity.QMessageTemplate;
import com.eactive.apim.portal.template.repository.MessageTemplateRepository;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.StringPath;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class MessageTemplateService  extends AbstractDataService<MessageTemplate, String, MessageTemplateRepository> {

    public Page<MessageTemplate> findAll(Pageable pageable, MessageTemplateSearch messageTemplateSearch) {
    	QMessageTemplate qMessageTemplate = QMessageTemplate.messageTemplate;

    	BooleanBuilder predicate = new BooleanBuilder();

    	if(StringUtils.isNotBlank(messageTemplateSearch.getSearchMessageSubject())) {
    		predicate = predicate.and(qMessageTemplate.messageName
    						.containsIgnoreCase(messageTemplateSearch.getSearchMessageSubject()));
    	}

    	if(StringUtils.isNotBlank(messageTemplateSearch.getSearchMessageCode())) {
    		StringPath messageCodeStr = (StringPath) qMessageTemplate.messageCode.stringValue();
    		predicate = predicate.and(messageCodeStr.containsIgnoreCase(messageTemplateSearch.getSearchMessageCode()));
    	}

		// 활성화 조건 추가
		if (StringUtils.isNotBlank(messageTemplateSearch.getSearchEnableSms())) {
			predicate = predicate.and(qMessageTemplate.enableSms.eq(messageTemplateSearch.getSearchEnableSms()));
		}

		if (StringUtils.isNotBlank(messageTemplateSearch.getSearchEnableEmail())) {
			predicate = predicate.and(qMessageTemplate.enableEmail.eq(messageTemplateSearch.getSearchEnableEmail()));
		}

		if (StringUtils.isNotBlank(messageTemplateSearch.getSearchEnableMessenger())) {
            predicate.and(qMessageTemplate.enableMessenger.eq(messageTemplateSearch.getSearchEnableMessenger()));
        }

    	return repository.findAll(predicate, pageable);
	}
}
