package com.eactive.eai.rms.data.entity.onl.apim.apigroup;

import com.eactive.eai.data.entity.onl.apim.apigroup.ApiGroup;
import com.eactive.eai.data.entity.onl.apim.apigroup.ApiGroupApi;
import com.eactive.eai.data.entity.onl.apim.apigroup.QApiGroup;
import com.eactive.eai.data.entity.onl.apim.apigroup.QApiGroupApi;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.eactive.eai.rms.onl.apim.apigroup.ui.ApiGroupUISearch;
import com.querydsl.core.types.dsl.BooleanExpression;

import java.util.List;
import java.util.Optional;

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


@Service
@Transactional
public class ApiGroupService extends AbstractDataService<ApiGroup, String, ApiGroupRepository> {

	public Page<ApiGroup> selectList(ApiGroupUISearch apiGroupUISearch, Pageable pageable) {
		QApiGroup qApiGroup = QApiGroup.apiGroup;
		BooleanExpression predicate = qApiGroup.groupName.containsIgnoreCase(apiGroupUISearch.getSearchGroupName());
		
		if (StringUtils.isNotBlank(apiGroupUISearch.getSearchGroupDesc())) {
			predicate = predicate.and(qApiGroup.groupDesc.containsIgnoreCase(apiGroupUISearch.getSearchGroupDesc()));
		}

		if (StringUtils.isNotBlank(apiGroupUISearch.getSearchDisplayYn())) {
			predicate = predicate.and(qApiGroup.displayYn.eq(apiGroupUISearch.getSearchDisplayYn()));
		}
		return repository.findAll(predicate, pageable);
	}

	public Optional<ApiGroup> findByIdWithApiList(String id) {
		return repository.findById(id)
			.map(apiGroup -> {
				Hibernate.initialize(apiGroup.getApiGroupApiList());
				return apiGroup;
			});
	}

	public void deleteApiGroupApiByApiId(String apiId) {
		List<ApiGroup> apiGroups = repository.findAll();
		for (ApiGroup apiGroup : apiGroups) {
			List<ApiGroupApi> apiGroupApis = apiGroup.getApiGroupApiList();
			apiGroupApis.removeIf(apiGroupApi -> apiGroupApi.getId().getApiId().equals(apiId));
			repository.save(apiGroup);
		}
	}

	public List<ApiGroup> findByApiId(String apiId) {
		QApiGroup qApiGroup = QApiGroup.apiGroup;
		QApiGroupApi qApiGroupApi = QApiGroupApi.apiGroupApi;

		return getJPAQueryFactory().selectFrom(qApiGroup)
				.leftJoin(qApiGroup.apiGroupApiList, qApiGroupApi)
				.where(qApiGroupApi.id.apiId.eq(apiId))
				.distinct()
				.fetch();

	}
}
