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

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.b2bservice.B2BService;
import com.eactive.eai.data.entity.onl.b2bservice.B2BServiceId;
import com.eactive.eai.data.entity.onl.b2bservice.QB2BService;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.eactive.eai.rms.onl.manage.serviceinfo.b2bservice.B2bServiceUISearch;
import com.querydsl.core.types.dsl.BooleanExpression;

@Service
@Transactional
public class B2bServiceService extends AbstractDataService<B2BService, B2BServiceId, B2bServiceRepository> {

	public Page<B2BService> findPage(Pageable pageable, B2bServiceUISearch uiSearch) {
		BooleanExpression predicate = createPredicate(uiSearch);
		if (predicate == null)
			return repository.findAll(pageable);
		return repository.findAll(predicate, pageable);
	}
	
	public Iterable<B2BService> findAll(B2bServiceUISearch 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(B2bServiceUISearch uiSearch) {
		QB2BService qObject = QB2BService.b2BService;
		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);
	}
}
