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

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

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

import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.types.dsl.BooleanExpression;

@Service
@Transactional
public class ExtendedColumnDefinitionService
		extends AbstractDataService<ExtendedColumnDefinition, String, ExtendedColumnDefinitionRepository> {

	public Iterable<ExtendedColumnDefinition> findKeys() {
		QExtendedColumnDefinition qExtendedColumnDefinition = QExtendedColumnDefinition.extendedColumnDefinition;
		return repository.findAll(qExtendedColumnDefinition.isKey.eq("Y"), qExtendedColumnDefinition.orderSeq.asc());
	}

	@Override
	public List<ExtendedColumnDefinition> findAll() {
		QExtendedColumnDefinition q = QExtendedColumnDefinition.extendedColumnDefinition;
		List<ExtendedColumnDefinition> list = new ArrayList<>();
		repository.findAll(q.orderSeq.asc(), q.isKey.desc(), q.keySeq.asc(), q.columnName.asc()).iterator().forEachRemaining(list::add);
		return list;
	}

	public Page<ExtendedColumnDefinition> findAll(Pageable pageable, String searchColumnName, String searchColumnDesc) {
		QExtendedColumnDefinition qExtendedColumnDefinition = QExtendedColumnDefinition.extendedColumnDefinition;

		BooleanExpression predicate = qExtendedColumnDefinition.isNotNull();
		if (StringUtils.isNotBlank(searchColumnName)) {
			predicate = predicate.and(qExtendedColumnDefinition.columnName.containsIgnoreCase(searchColumnName));
		}

		if (StringUtils.isNotBlank(searchColumnDesc)) {
			predicate = predicate.and(qExtendedColumnDefinition.columnDesc.containsIgnoreCase(searchColumnDesc));
		}

		Pageable orderedPageable = PageRequest.of(
				pageable.getPageNumber(),
				pageable.getPageSize(),
				Sort.by(Sort.Order.asc("orderSeq"), Sort.Order.asc("columnName")));

		return repository.findAll(predicate, orderedPageable);
	}

}
