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

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

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

import com.eactive.eai.data.entity.onl.bizkey.BizKey;
import com.eactive.eai.data.entity.onl.bizkey.BizKeyId;
import com.eactive.eai.data.entity.onl.bizkey.QBizKey;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.BooleanBuilder;

@Transactional
@Service
public class BizKeyService extends AbstractDataService<BizKey, BizKeyId, BizKeyRepository> {

	public Page<BizKey> findAll(String searchEaiSvcName, Pageable pageable) {

		BooleanBuilder predicate = new BooleanBuilder();

		if (StringUtils.isNotBlank(searchEaiSvcName)) {
			predicate.and(QBizKey.bizKey.id.eaisvcname.containsIgnoreCase(searchEaiSvcName));
		}

		pageable.getSort().and(sortByDefault());

		return repository.findAll(predicate, pageable);
	}

	public void delete(String eaiSvcName, String etractDstcd) {
		this.findByIdEaisvcnameAndIdEtractdstcd(eaiSvcName, etractDstcd).forEach(this::delete);
	}
	
	public Iterable<BizKey> findByIdEaiSvcName(String eaiSvcName) {
		return repository.findAll(QBizKey.bizKey.id.eaisvcname.eq(eaiSvcName));
	}

	public void deleteByIdEaiSvcName(String eaiSvcName) {
		findByIdEaiSvcName(eaiSvcName).forEach(this::delete);
	}

	protected Sort sortByDefault() {
		List<Order> orders = new ArrayList<>();
		orders.add(Order.asc("id.eaisvcname"));
		orders.add(Order.asc("id.etractdstcd"));
		orders.add(Order.asc("id.fldprcssno"));
		return Sort.by(orders);
	}
	
	@Transactional(readOnly = true)
	public Collection<BizKey> findByIdEaisvcnameAndIdEtractdstcd(String eaiSvcCd, String exrClsNm) {
		return repository.findByIdEaisvcnameAndIdEtractdstcd(eaiSvcCd, exrClsNm, sortByDefault());
	}
}
