/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/reportportal/commons-dao
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.epam.ta.reportportal.triggers;

import com.epam.ta.reportportal.database.dao.LogRepository;
import com.epam.ta.reportportal.database.entity.item.RetryType;
import com.epam.ta.reportportal.database.entity.item.TestItem;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent;
import org.springframework.stereotype.Service;

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

import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.StreamSupport.stream;

/**
 * @author Dzmitry Kavalets
 */
@Service
public class DeleteItemsListener extends AbstractMongoEventListener<TestItem> {

	private MongoTemplate mongoTemplate;
	private LogRepository logRepository;
	private QueryMapper queryMapper;
	private MongoMappingContext mappingContext;

	@Autowired
	public DeleteItemsListener(MongoTemplate mongoTemplate, LogRepository logRepository, MongoMappingContext mappingContext) {
		this.mongoTemplate = mongoTemplate;
		this.logRepository = logRepository;
		this.queryMapper = new QueryMapper(mongoTemplate.getConverter());
		this.mappingContext = mappingContext;
	}

	@Override
	public void onBeforeDelete(BeforeDeleteEvent<TestItem> event) {
		DBObject dbqo = queryMapper.getMappedObject(event.getDBObject(), mappingContext.getPersistentEntity(TestItem.class));
		for (DBObject dbObject : mongoTemplate.getCollection(event.getCollectionName()).find(dbqo)) {

			Optional<RetryType> retryType = RetryType.fromString((String) dbObject.get("retryType"));
			final String id = dbObject.get("_id").toString();
			final BasicDBObject itemDescendantsQuery = new BasicDBObject("path", new BasicDBObject("$in", singletonList(id)));

			if (!retryType.isPresent()) {
				clearData(event.getCollectionName(), itemDescendantsQuery, id);
			}

			if (retryType.isPresent() && retryType.get().equals(RetryType.LAST)) {
				itemDescendantsQuery.append("retries.path", new BasicDBObject("$in", singletonList(id)));
				clearData(event.getCollectionName(), itemDescendantsQuery, id);
			}
		}
	}

	private void clearData(String collectionName, BasicDBObject itemDescendantsQuery, String id) {
		final List<String> itemIds = stream(
				mongoTemplate.getCollection(collectionName).find(itemDescendantsQuery).spliterator(), false).map(
				it -> it.get("_id").toString()).collect(toList());
		mongoTemplate.getCollection(collectionName).remove(itemDescendantsQuery);
		itemIds.add(id);
		logRepository.deleteByItemRef(itemIds);
	}

}

@@ -1576,35 +1576,8 @@
 ist;
-%0Aimport java.util.Optional;
 %0A%0Aim
@@ -2335,16 +2335,17 @@
 xt;%0A%09%7D%0A%0A
+%0A
 %09@Overri
@@ -2632,426 +2632,170 @@
 ) %7B%0A
-%0A%09%09%09Optional%3CRetryType%3E retryType = RetryType.fromString((String) dbObject.get(%22retryType%22));%0A%09%09%09final String id = dbObject.get(%22_id%22).toString();%0A%09%09%09final BasicDBObject itemDescendantsQuery = new BasicDBObject(%22path%22, new BasicDBObject(%22$in%22, singletonList(id)));%0A%0A%09%09%09if (!retryType.isPresent()) %7B%0A%09%09%09%09clearData(event.getCollectionName(), itemDescendantsQuery, id);%0A%09%09%09%7D%0A%0A%09%09%09if (retryType.isPresent() && retryType.get
+%09%09%09final String id = dbObject.get(%22_id%22).toString();%0A%09%09%09String retryType = (String) dbObject.get(%22retryType%22);%0A%09%09%09if (retryType == null %7C%7C RetryType.LAST.getValue
 ().e
@@ -2800,25 +2800,25 @@
 .equals(
-R
+r
 etryType
 .LAST)) 
@@ -2809,21 +2809,16 @@
 etryType
-.LAST
 )) %7B%0A%09%09%09
@@ -2822,275 +2822,125 @@
 %09%09%09%09
-itemDescendantsQuery.append(%22retries.path%22, new BasicDBObject(%22$in%22, singletonList(id)));%0A%09%09%09%09clearData(event.getCollectionName(), itemDescendantsQuery, id);%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D%0A%0A%09private void clearData(String collectionName, BasicDBObject itemDescendantsQuery, String id) %7B%0A
+final BasicDBObject itemDescendantsQuery = new BasicDBObject(%22path%22, new BasicDBObject(%22$in%22, singletonList(id)));%0A%09%09
 %09%09fi
@@ -2973,21 +2973,16 @@
  stream(
-%0A%09%09%09%09
 mongoTem
@@ -2993,33 +2993,42 @@
 e.getCollection(
-c
+event.getC
 ollectionName).f
@@ -3024,16 +3024,18 @@
 tionName
+()
 ).find(i
@@ -3086,16 +3086,18 @@
 ap(%0A%09%09%09%09
+%09
+%09
 it -%3E it
@@ -3139,16 +3139,18 @@
 ist());%0A
+%09%09
 %09%09mongoT
@@ -3171,17 +3171,26 @@
 lection(
-c
+event.getC
 ollectio
@@ -3194,16 +3194,18 @@
 tionName
+()
 ).remove
@@ -3228,16 +3228,18 @@
 Query);%0A
+%09%09
 %09%09itemId
@@ -3251,16 +3251,18 @@
 (id);%0A%09%09
+%09
+%09
 logRepos
@@ -3294,13 +3294,21 @@
 mIds);%0A%09
+%09%09%7D%0A%09%09%7D%0A%09
 %7D
-%0A
 %0A%7D%0A

update trigger