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

import java.util.Comparator;

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;

import com.eactive.eai.data.entity.onl.property.PropGroup;
import com.eactive.eai.data.entity.onl.property.QPropGroup;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.eactive.eai.rms.onl.manage.comm.property.PropertyGroupUI;
import com.querydsl.core.types.dsl.BooleanExpression;

@Service
@Transactional
public class PropertyGroupService extends AbstractDataService<PropGroup, String, PropGroupRepository> {

	public Page<PropGroup> findAll(Pageable pageable, PropertyGroupUI propertyGroupUI) {

		QPropGroup qPropGroup = QPropGroup.propGroup;

		BooleanExpression predicate = qPropGroup.prptygroupname
				.containsIgnoreCase(propertyGroupUI.getSearchPrptyGroupName())
				.and(qPropGroup.prptygroupdesc.containsIgnoreCase(propertyGroupUI.getSearchPrptyGroupDesc()));

		if (StringUtils.isNotBlank(propertyGroupUI.getSearchPrptyName())) {
			predicate = predicate
					.and(qPropGroup.props.any().id.prptyname.containsIgnoreCase(propertyGroupUI.getSearchPrptyName()));
		}
		if (StringUtils.isNotBlank(propertyGroupUI.getSearchPrpty2Val())) {
			predicate = predicate
					.and(qPropGroup.props.any().prpty2val.containsIgnoreCase(propertyGroupUI.getSearchPrpty2Val()));
		}
		return repository.findAll(predicate, pageable);
	}

	public PropGroup getByIdWithSortedProps(String prptyGroupName) {
		PropGroup propGroup = getById(prptyGroupName);
		if (propGroup != null && propGroup.getProps() != null) {
			propGroup.getProps().sort(Comparator.comparing(p -> p.getId().getPrptyname()));
		}
		return propGroup;
	}
}
