package com.eactive.eai.authserver.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.authserver.ScopeEntity;

@Service
@Transactional
public class ScopeDAO extends BaseDAO {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	@Autowired
	private ScopeLoader scopeLoader;

	public Map<String, HashSet<String>> loadApiScopeRelations() throws DAOException {
		try {
			Stream<ScopeEntity> scopeEntities = scopeLoader.loadAll();
			Map<String, HashSet<String>> clientEntitymap = new HashMap<>();

			scopeEntities.forEach(scopeEntity -> {
				String apiId = scopeEntity.getId().getBzwksvckeyname();
				HashSet<String> scopeSet = clientEntitymap.get(apiId);
				if (scopeSet == null) {
					scopeSet = new HashSet<String>();
					clientEntitymap.put(apiId, scopeSet);
				}
				String scopeId = scopeEntity.getId().getScopeid();
				clientEntitymap.get(apiId).add(scopeId);
//				clientEntitymap.put(scopeId, set);
			});
			return clientEntitymap;

		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
		}
	}

	public HashSet<String> getApiScopeRelationsByApiId(String apiId) throws DAOException {
		try {
			HashSet<String> scopeSet = new HashSet<>();

			ScopeEntity scopeEntity = scopeLoader.findByIdBzwksvckeyname(apiId);

			scopeSet.add(scopeEntity.getId().getScopeid());
			return scopeSet;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
		}

	}

	public List<String> getApiScopeRelationsByScopeId(String scopeId) throws DAOException {
		try {
			List<String> apiList = new ArrayList<>();
			ScopeEntity scopeEntity = scopeLoader.findByIdScopeid(scopeId);
			apiList.add(scopeEntity.getId().getBzwksvckeyname());

			return apiList;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
		}

	}

	public boolean hasApiScopeRelation(String apiId, String scopeId) throws DAOException {
		try {
			ScopeEntity scopeEntity = scopeLoader.findByIdBzwksvckeynameAndIdScopeid(apiId, scopeId);
			return scopeEntity != null;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
		}

	}
}
