package dev.banking.model;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BankAccount {

    private final int accountId;
    private long balance;

    public final ReentrantLock lock = new ReentrantLock();
    private final Condition sufficientFundsCondition = lock.newCondition();

    public BankAccount(int accountId, long initialBalance) {
        this.accountId = accountId;
        this.balance = initialBalance;
    }

    public int getAccountId() {
        return accountId;
    }

    public long getBalance() {
        lock.lock();
        try {
            return balance;
        } finally {
            lock.unlock();
        }
    }

    public void deposit(long amount) {
        if (amount <= 0) return;

        lock.lock();
        try {
            balance += amount;
            //Bonus Task
            sufficientFundsCondition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void withdraw(long amount) {
        if (amount <= 0) return;

        lock.lock();
        try {
            //Bonus Task
            while (balance < amount) {
                try {
                    boolean receivedSignal = sufficientFundsCondition.await(50, TimeUnit.MILLISECONDS);
                    if (!receivedSignal && balance < amount) {
                        return;
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
            balance -= amount;
        } finally {
            lock.unlock();
        }
    }

    public void transfer(BankAccount target, long amount) {
        if (target == null || this == target || amount <= 0) return;

        BankAccount firstAccount = this.accountId < target.getAccountId() ? this : target;
        BankAccount secondAccount = firstAccount == this ? target : this;

        firstAccount.lock.lock();
        secondAccount.lock.lock();

        try {
            //Bonus Task
            while (this.balance < amount) {
                try {
                    secondAccount.lock.unlock();

                    boolean receivedSignal = this.sufficientFundsCondition.await(50, TimeUnit.MILLISECONDS);

                    secondAccount.lock.lock();

                    if (!receivedSignal && this.balance < amount) {
                        return;
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }

            this.balance -= amount;
            target.balance += amount;

            //Bonus Task
            target.sufficientFundsCondition.signalAll();

        } finally {
            secondAccount.lock.unlock();
            firstAccount.lock.unlock();
        }
    }
}