package com.workfusion.odf.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;

import com.amazonaws.SdkBaseException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.workfusion.odf.api.domain.Document;
import com.workfusion.odf.api.domain.Transaction;
import com.workfusion.rpa.core.storage.S3Manager;

public class DeleteTransactionServiceImpl implements DeleteTransactionService {
    private final TransactionService transactionService;
    private final S3Manager s3Manager;
    private final Logger logger;

	@Inject
    public DeleteTransactionServiceImpl(final TransactionService transactionService, final S3Manager s3Manager, final Logger logger) {
        this.transactionService = transactionService;
		this.s3Manager = s3Manager;
		this.logger = logger;
	}

    @Override
	public void deleteTransaction(final String transactionId) {
		Transaction transaction = transactionService.byId(transactionId);
		if (transaction != null) {
			Map<String, Boolean> s3Links = new HashMap<>();

			List<Document> documents = transaction.getDocs();
			logger.info("Delete transaction, id={}, documents: {}", transactionId, (documents != null) ? documents.size() : "<NULL>");
			if (documents != null) {
				for (Document document : documents) {
					removeDocumentS3Links(document, s3Links);
				}
			}

			// Delete Intake transaction itself
	        transactionService.delete(transactionId);

			logger.info("Transaction id={} deleted", transactionId);
		}
    }

	private void removeDocumentS3Link(final String s3Link, final Map<String, Boolean> s3Links) {
		if (StringUtils.isNotEmpty(s3Link) && !s3Links.containsKey(s3Link)) {
			try {
				s3Manager.deleteFile(s3Link);
			} catch (SdkBaseException ex) {
				logger.error("Error deleting S3 file '" + s3Link + "'", ex);
			}
			s3Links.put(s3Link, Boolean.TRUE);
		}
	}

	private void removeDocumentS3Links(final Document document, final Map<String, Boolean> s3Links) {
		removeDocumentS3Link(document.getOriginalDocumentLink(), s3Links);
		removeDocumentS3Link(document.getTaggedTextLink(), s3Links);
		removeDocumentS3Link(document.getTextLink(), s3Links);

		Document origin = document.getOrigin();
		if (origin != null) {
			removeDocumentS3Links(origin, s3Links);
		}
	}
}
