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

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.entity.onl.adapter.AdapterProp;
import com.eactive.eai.data.entity.onl.adapter.AdapterPropId;
import com.eactive.eai.data.entity.onl.adapter.QAdapter;
import com.eactive.eai.data.entity.onl.adapter.QAdapterGroup;
import com.eactive.eai.data.entity.onl.adapter.QAdapterProp;
import com.eactive.eai.data.entity.onl.adapter.QAdapterPropGroup;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;

@Service
@Transactional
public class AdapterPropService extends AbstractDataService<AdapterProp, AdapterPropId, AdapterPropEMSRepository> {

	public List<Map<String, String>> findSnaAppcodeProps(String searchPrptygroupName) {
		QAdapterGroup qAdapterGroup = QAdapterGroup.adapterGroup;
		QAdapter qAdapter = QAdapter.adapter;
		QAdapterPropGroup qAdapterPropGroup = QAdapterPropGroup.adapterPropGroup;
		QAdapterProp qAdapterProp = QAdapterProp.adapterProp;

		JPAQuery<Tuple> query = getJPAQueryFactory()
				.select(qAdapter.id.adptrbzwkname, qAdapterProp.prpty2val)
				.from(qAdapterGroup)
				.join(qAdapterGroup.adapters, qAdapter)
				.join(qAdapter.adapterPropGroup, qAdapterPropGroup)
				.join(qAdapterPropGroup.adapterProps, qAdapterProp)
				.where(qAdapterGroup.adptrcd.eq("SNA"), qAdapterProp.id.prptyname.eq("APP_CODE"));

		if (searchPrptygroupName != null && !searchPrptygroupName.isEmpty()) {
			query.where(qAdapterProp.id.prptygroupname.eq(searchPrptygroupName));
		}

		query.orderBy(qAdapterGroup.adptrbzwkgroupname.asc());

		List<Tuple> result = query.fetch();

		return result.stream().map(t -> {
			Map<String, String> map = new HashMap<>();
			map.put("ADPTRBZWKNAME", t.get(qAdapter.id.adptrbzwkname));
			map.put("PRPTY2VAL", t.get(qAdapterProp.prpty2val));
			return map;
		}).collect(Collectors.toList());
	}

}
