package ru.job4j.Counter;

import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;


@ThreadSafe
public class UserStorage {
    @GuardedBy("this")
    private User[] usersContainer;
    private int size;
    public UserStorage(){
        usersContainer = new User[0];
        size = 0;
    }
    public synchronized void add (User user){
       User[] temp = new User[size + 1];
       System.arraycopy(usersContainer, 0, temp, 0, size);
       temp[size++] = user;
       usersContainer = temp;
    }

    private synchronized int find(int id){
        int idFound = -1;
        for(int i = 0; i < size; ++i){
            if(usersContainer[i].getId() == id) {
                idFound = i;
                break;
            }
        }
        return idFound;
    }

    public synchronized boolean update(User user){
        int foundId = this.find(user.getId());
        boolean updateCompleted = false;
        if(foundId >= 0){
            usersContainer[foundId].setAmount(user.getAmount());
            updateCompleted = true;
        }
        return updateCompleted;
    }

    public synchronized boolean delete(User user){
        boolean deleteCompeted = false;
        int foundId = this.find(user.getId());
        if(foundId >= 0) {
            User[] temp = new User[--size];
            for(int i = 0, j = 0; i < size + 1; i++, j++) {
                if (i != foundId)
                    temp[j] = usersContainer[i];
                else
                    j--;
            }
            usersContainer = temp;
            deleteCompeted = true;
        }
        return deleteCompeted;
    }
    public synchronized boolean transfer(int fromId, int toId, int amount){
        boolean transferCompleted = false;
        int foundFrom = find(fromId);
        int foundTo = find(toId);
        if(foundFrom != -1 && foundTo != -1) {
            User userFrom = usersContainer[foundFrom];
            User userTo = usersContainer[foundTo];
            if(userFrom.getAmount() - amount >= 0){
                userFrom.setAmount(userFrom.getAmount() - amount);
                userTo.setAmount(userTo.getAmount() + amount);
                transferCompleted = true;
            }
        }
        return transferCompleted;
    }


    public synchronized User[] getUsersContainer() {
        return usersContainer;
    }

    public int getSize() {
        return size;
    }
}
