package dev.banking.model;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class BankAccount {

    private final int accountId;
    private long balance;
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();

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

    public int getAccountId() {
        return accountId;
    }

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

    public void deposit(long amount) {
        writeLock.lock();
        try
        {
            balance += amount;
        } finally
        {
            writeLock.unlock();
        }
    }

    public void withdraw(long amount) {
        writeLock.lock();
        try
        {
            balance -= amount;
        } finally
        {
            writeLock.unlock();
        }
    }

    public void transfer(BankAccount target, long amount) {
        if (target == this)
        {
            return;
        }
        BankAccount first = this;
        BankAccount second = target;

        if (this.getAccountId() > target.getAccountId())
        {
            first = target;
            second = this;
        }


        first.writeLock.lock();
        try
        {
            second.writeLock.lock();
            try
            {
                //"first" and "second":only for the order of locking to prevent deadlock (have nothing to do with the direction of the transfer)
                this.balance -= amount;
                target.balance += amount;
            } finally
            {
                second.writeLock.unlock();
            }
        } finally
        {
            first.writeLock.unlock();
        }
    }

}