package at.spengergasse.service;

import at.spengergasse.domain.Account;
import at.spengergasse.domain.AccountException;
import at.spengergasse.repository.AccountRepository;
import com.github.javafaker.Faker;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BankService {
    private final AccountRepository repository;

    public BankService(AccountRepository repository) {
        this.repository = repository;

        if (repository.count() == 0)
            fillTestData(500);
    }

    public void fillTestData(int count) {
        String[] accounttypes = { "Checking", "Savings", "Fixed Deposit", "Business", "Joint" };
        Account   a;
        Faker     faker = new Faker();
        String    firstName;
        LocalDate openingDate;
        String    accountType;
        Double    amount;
        Boolean   active;

        for (int i=0; i<count; i++) {
            firstName = faker.address().firstName();
            openingDate = LocalDate.now().minusDays((int) Math.random() * 3650);
            accountType = accounttypes[faker.random().nextInt(0, accounttypes.length - 1)];
            amount = faker.number().randomDouble(2, 0, 50000);
            active = faker.bool().bool();
            a = new Account(firstName, openingDate, accountType, amount, active);
            repository.save(a);
        }
    }

    public ArrayList<Account> findAll() {
        ArrayList<Account> copy;
        copy = (ArrayList<Account>) repository.findAll();
        return copy;
    }

    @Override
    public String toString() {
        return repository.findAll().stream()
                .map(s -> s.toString())
                .collect(Collectors.joining("\n"));
    }

    public void removeAllAccouts() {
        repository.deleteAll();
    }

    public void addAccount(Account a) {
        repository.save(a);
    }

    public void remove1(Long accountId) {
        if (accountId == null)
            throw new AccountException("Fehler: kein Account!");

        Optional<Account> gef = repository.findById(accountId);
        if (gef.isEmpty())
            throw new AccountException("Fehler: Account wurde bereits gelöscht!");
        //repository.existsById(accountId) => boolean

        repository.deleteById(accountId);
    }

    public void add100Eur(Long accountId) {
        repository.findAll().stream()
                .filter(a -> a.getAccountId().equals(accountId))
                .forEach(a -> a.setAmount(a.getAmount()+100));
    }
}
