package org.marsik.elshelves.backend.services;

import org.marsik.elshelves.api.entities.TransactionApiModel;
import org.marsik.elshelves.backend.controllers.exceptions.OperationNotPermitted;
import org.marsik.elshelves.backend.entities.Purchase;
import org.marsik.elshelves.backend.entities.Transaction;
import org.marsik.elshelves.backend.entities.User;
import org.marsik.elshelves.backend.entities.converters.EmberToTransaction;
import org.marsik.elshelves.backend.entities.converters.TransactionToEmber;
import org.marsik.elshelves.backend.repositories.BoxRepository;
import org.marsik.elshelves.backend.repositories.PurchaseRepository;
import org.marsik.elshelves.backend.repositories.SourceRepository;
import org.marsik.elshelves.backend.repositories.TransactionRepository;
import org.marsik.elshelves.backend.repositories.TypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TransactionService extends AbstractRestService<TransactionRepository, Transaction, TransactionApiModel> {
	@Autowired
	SourceRepository sourceRepository;

	@Autowired
	PurchaseRepository purchaseRepository;

	@Autowired
	BoxRepository boxRepository;

	@Autowired
	TypeRepository typeRepository;

	@Autowired
	PurchaseService purchaseService;

	@Autowired
	public TransactionService(TransactionRepository repository,
							  TransactionToEmber dbToRest,
							  EmberToTransaction restToDb,
							  UuidGenerator uuidGenerator) {
		super(repository, dbToRest, restToDb, uuidGenerator);
	}

	@Override
	protected Transaction createEntity(TransactionApiModel dto, User currentUser) {
		Transaction t = super.createEntity(dto, currentUser);

		for (Purchase p: t.getItems()) {
			if (p.getOwner() == null) {
				p.setOwner(currentUser);
			}

			if (p.getUuid() == null) {
				p.setUuid(getUuidGenerator().generate());
			}
		}

		return t;
	}

	@Override
	protected void deleteEntity(Transaction entity) throws OperationNotPermitted {
		for (Purchase p: entity.getItems()) {
			purchaseService.deleteEntity(p);
		}

		super.deleteEntity(entity);
	}

    @Override
    protected Iterable<Transaction> getAllEntities(User currentUser) {
        return getRepository().findByOwner(currentUser);
    }
}

@@ -949,16 +949,40 @@
 rvice;%0A%0A
+import java.util.Date;%0A%0A
 @Service
@@ -1679,16 +1679,80 @@
 User) %7B%0A
+%09%09if (dto.getDate() == null) %7B%0A%09%09%09dto.setDate(new Date());%0A%09%09%7D%0A%0A
 %09%09Transa

Add current date to transaction if not provided