package market.guess.ui.client; import java.util.ArrayList; import java.util.List; import market.guess.api.AccountContext; import market.guess.api.Result; import market.guess.model.ledger.LedgerDTO; import okhttp3.FormBody; /** * Accounts over HTTP. Only our own ledger is ours to read; the server shows other users as name * and balance, so they appear here as accounts without entries, after our own. */ public final class RemoteAccountContext implements AccountContext { private final ServerClient client; public RemoteAccountContext(ServerClient client) { this.client = client; } @Override public Result> getAllAccounts() { var snapshot = client.snapshot(); var own = snapshot.account(); var all = new ArrayList(); if (own != null) { all.add(own); } for (var u : snapshot.users()) { if (own == null || !u.username().equalsIgnoreCase(own.owner())) { all.add(new LedgerDTO(u.username(), u.balance(), false, List.of())); } } return Result.ok(all); } @Override public Result getAccount(String owner) { return getAllAccounts().getData().stream() .filter(a -> a.owner().equalsIgnoreCase(owner)) .findFirst() .map(Result::ok) .orElseGet(() -> Result.error("Account not found")); } @Override public Result deposit(String owner, String amount) { Result res = client.post( LedgerDTO.class, new FormBody.Builder().add("amount", amount).build(), "user", "deposit"); client.pull(); return res; } }