/*
 * 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.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static java.util.Collections.singletonList;

/**
 * @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)) {
			String retryType = (String) dbObject.get("retryType");
			if (retryType == null || RetryType.LAST.getValue().equals(retryType)) {
				final String id = dbObject.get("_id").toString();
				Query itemDescendantsQuery = Query.query(Criteria.where("path").in(singletonList(id)));
				List<TestItem> itemsForDelete = mongoTemplate.find(itemDescendantsQuery, TestItem.class);
				List<String> ids = getDeletingItemsIds(itemsForDelete);
				ids.add(id);

				BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$in", ids));
				mongoTemplate.getCollection(event.getCollectionName()).remove(query);
				logRepository.deleteByItemRef(ids);
			}
		}
	}

	private List<String> getDeletingItemsIds(List<TestItem> itemsForDelete) {
		List<String> ids = new ArrayList<>();
		itemsForDelete.forEach(item -> {
			ids.add(item.getId());
			if (null != item.getRetries()) {
				item.getRetries().forEach(it -> ids.add(it.getId()));
			}
		});
		return ids;
	}
}

@@ -1070,24 +1070,56 @@
 b.DBObject;%0A
+import org.bson.types.ObjectId;%0A
 import org.s
@@ -1803,16 +1803,66 @@
 tonList;
+%0Aimport static java.util.stream.Collectors.toList;
 %0A%0A/**%0A *
@@ -2905,17 +2905,29 @@
  String 
-i
+deletingItemI
 d = dbOb
@@ -2954,16 +2954,17 @@
 ring();%0A
+%0A
 %09%09%09%09Quer
@@ -3040,17 +3040,29 @@
 tonList(
-i
+deletingItemI
 d)));%0A%09%09
@@ -3153,16 +3153,17 @@
 class);%0A
+%0A
 %09%09%09%09List
@@ -3167,73 +3167,155 @@
 ist%3C
-String%3E ids = getDeletingItems
+ObjectId%3E objectIds = itemsForDelete.stream().map(it -%3E new Object
 Id
-s
 (it
-emsForDelete);%0A%09%09%09%09ids.add(id
+.getId())).collect(toList());%0A%09%09%09%09objectIds.add(new ObjectId(deletingItemId)
 );%0A%0A
@@ -3390,17 +3390,23 @@
 (%22$in%22, 
-i
+objectI
 ds));%0A%09%09
@@ -3476,16 +3476,99 @@
 (query);
+%0A%0A%09%09%09%09List%3CString%3E itemRefs = getLogItemReferences(itemsForDelete, deletingItemId);
 %0A%09%09%09%09log
@@ -3595,17 +3595,22 @@
 temRef(i
-d
+temRef
 s);%0A%09%09%09%7D
@@ -3647,23 +3647,24 @@
  get
-DeletingItemsId
+LogItemReference
 s(Li
@@ -3690,16 +3690,27 @@
 orDelete
+, String id
 ) %7B%0A%09%09Li
@@ -3745,16 +3745,31 @@
 st%3C%3E();%0A
+%09%09ids.add(id);%0A
 %09%09itemsF

convert to object ids