class AssetGroupExceptionServiceImpl implements AssetGroupExceptionService {

	@Override
	public StickyExceptionResponse getAllTargetTypesByExceptionNameAndDataSource(final String exceptionName, final String dataSource) throws PacManException {
		Set<String> selectedTargetTypes = Sets.newHashSet();
		StickyExceptionResponse stickyExceptionResponse = new StickyExceptionResponse();
		List<AssetGroupExceptionProjections> allAssetGroupExceptions = assetGroupExceptionRepository.findAllAssetGroupExceptions(exceptionName, dataSource);
		List<TargetTypeRuleViewDetails> allTargetTypeRuleDetails = Lists.newArrayList();
		List<String> ruleIdList = Lists.newArrayList();
		TargetTypeRuleViewDetails targetTypeRuleDetails = new TargetTypeRuleViewDetails();
		int exceptionSize = allAssetGroupExceptions.size();
		for (int index = 0; index<exceptionSize; index++) {
			AssetGroupExceptionProjections assetGroupException = allAssetGroupExceptions.get(index);
			String targetType = assetGroupException.getTargetType();
			if(StringUtils.isNotBlank(assetGroupException.getRuleId())) {
				ruleIdList.add(assetGroupException.getRuleId());
			}

			if(StringUtils.isNotBlank(targetType)) {
				selectedTargetTypes.add(targetType);
				targetTypeRuleDetails.setTargetName(assetGroupException.getTargetType());
				targetTypeRuleDetails.setAdded(true);
				if(isNotLast(index, exceptionSize)) {
					if(!allAssetGroupExceptions.get(1+index).getTargetType().equals(targetType)){
						allTargetTypeRuleDetails.add(getTargetTypeRuleDetails(ruleIdList, targetTypeRuleDetails, targetType));
						ruleIdList.clear();
						targetTypeRuleDetails = new TargetTypeRuleViewDetails();
					}
				} else {
					allTargetTypeRuleDetails.add(getTargetTypeRuleDetails(ruleIdList, targetTypeRuleDetails, targetType));
					ruleIdList.clear();
					targetTypeRuleDetails = new TargetTypeRuleViewDetails();
				}
			}
		}
		
		stickyExceptionResponse.setExceptionName(allAssetGroupExceptions.get(0).getExceptionName()); 
		stickyExceptionResponse.setExceptionReason(allAssetGroupExceptions.get(0).getExceptionReason());
		stickyExceptionResponse.setExpiryDate(allAssetGroupExceptions.get(0).getExpiryDate());
		stickyExceptionResponse.setDataSource(allAssetGroupExceptions.get(0).getDataSource());
		
		Set<String> allSelectedTargetTypes = Sets.newHashSet();
		allSelectedTargetTypes.addAll(selectedTargetTypes);
		
		List<TargetTypeRuleViewDetails> remainingTargetTypeDetails = assetGroupTargetDetailsService.getTargetTypesByAssetGroupIdAndTargetTypeNotIn(allAssetGroupExceptions.get(0).getAssetGroup(), allSelectedTargetTypes);
		allTargetTypeRuleDetails.addAll(remainingTargetTypeDetails);
		
		stickyExceptionResponse.setTargetTypes(allTargetTypeRuleDetails);
		stickyExceptionResponse.setGroupName(allAssetGroupExceptions.get(0).getAssetGroup());
		return stickyExceptionResponse;
	}

}