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

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.entity.onl.c2rservice.C2RService;
import com.eactive.eai.data.entity.onl.c2rservice.C2RServiceId;
import com.eactive.eai.data.entity.onl.c2rservice.QC2RService;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.types.dsl.BooleanExpression;

@Service
@Transactional
public class C2rServiceService extends AbstractDataService<C2RService, C2RServiceId, C2RServiceRepository> {

	public Page<C2RService> findPage(Pageable pageable, C2rServiceSearch uiSearch) {
		BooleanExpression predicate = createPredicate(uiSearch);
		if (predicate == null)
			return repository.findAll(pageable);
		return repository.findAll(predicate, pageable);
	}
	
	public Iterable<C2RService> findAll(C2rServiceSearch uiSearch) {
		BooleanExpression predicate = createPredicate(uiSearch);
		Sort sort = Sort.by(Direction.ASC, "id.extnlinstiidnfiname");
		if (predicate == null)
			return repository.findAll(sort);
		return repository.findAll(predicate, sort);
	}

	private BooleanExpression createPredicate(C2rServiceSearch uiSearch) {
		QC2RService qObject = QC2RService.c2RService;
		BooleanExpression predicate = null;
		if (StringUtils.isNotBlank(uiSearch.getSearchExtnlInstiIdnfiName())) {
			predicate = andExpression(predicate, qObject.id.extnlinstiidnfiname.upper()
					.containsIgnoreCase(uiSearch.getSearchExtnlInstiIdnfiName().toUpperCase()));
		}

		if (StringUtils.isNotBlank(uiSearch.getSearchPsvSysAdptBzwkGroupName())) {
			predicate = andExpression(predicate, qObject.psvsysadptrbzwkgroupname.upper()
					.containsIgnoreCase(uiSearch.getSearchPsvSysAdptBzwkGroupName().toUpperCase()));
		}

		if (StringUtils.isNotBlank(uiSearch.getSearchPsvSysBzwkDstcd())) {
			predicate = andExpression(predicate,
					qObject.psvsysbzwkdstcd.containsIgnoreCase(uiSearch.getSearchPsvSysBzwkDstcd().toUpperCase()));
		}

		if (StringUtils.isNotBlank(uiSearch.getSearchFailOverYn())) {
			predicate = andExpression(predicate, qObject.flovryn.eq(uiSearch.getSearchFailOverYn()));
		}

		if (StringUtils.isNotBlank(uiSearch.getSearchUseYn())) {
			predicate = andExpression(predicate, qObject.useyn.eq(uiSearch.getSearchUseYn()));
		}
		return predicate;
	}
	
	private BooleanExpression andExpression(BooleanExpression predicate, BooleanExpression right) {
		return predicate == null ? right : predicate.and(right);
	}
}
