package com.ufund.api.ufundapi.persistence;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ufund.api.ufundapi.model.User;
@Component
public class UserFileDAO implements UserDAO {
private final Map<String, User> users; // cache
private final ObjectMapper objectMapper;
private final String filename;
public UserFileDAO(@Value("${users.file}") String filename, ObjectMapper objectMapper) throws IOException {
this.filename = filename;
this.objectMapper = objectMapper;
users = new HashMap<>();
load(); // load the users from the file
}
/**
* Load changes from the json file
*
* @throws IOException Any IO issue with the file
*/
private void load() throws IOException {
users.clear();
User[] usersArray = objectMapper.readValue(new File(filename), User[].class);
for (User user : usersArray) {
users.put(user.getUsername(), user);
}
}
/**
* Saves the needs to json
*
* @throws IOException If there was an IO issue saving the file
*/
private void save() throws IOException {
objectMapper.writeValue(new File(filename), users.values());
}
@Override
public User[] getUsers() {
synchronized (users) {
return users.values().toArray(User[]::new);
}
}
@Override
public User getUser(String username) {
synchronized (users) {
return users.getOrDefault(username, null);
}
}
@Override
public User addUser(User user) throws IOException {
synchronized (users) {
var res = users.putIfAbsent(user.getUsername(), user);
save();
if (res == null) {
return user;
}
return res;
}
}
@Override
public User updateUser(User user) throws IOException {
synchronized (users) {
if (users.containsKey(user.getUsername())) {
var old = users.put(user.getUsername(), user);
user.copyPassword(Objects.requireNonNull(old));
save();
return user;
} else {
return null;
}
}
}
@Override
public boolean deleteUser(String username) throws IOException {
synchronized (users) {
if (users.containsKey(username)) {
users.remove(username);
save();
return true;
} else {
return false;
}
}
}
}