/*
 * This file is part of Bisq.
 *
 * Bisq is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * Bisq is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
 */

package bisq.network.p2p.storage.persistence;

import bisq.network.p2p.storage.P2PDataStorage;
import bisq.network.p2p.storage.payload.PersistableNetworkPayload;

import javax.inject.Inject;

import com.google.common.annotations.VisibleForTesting;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * Used for PersistableNetworkPayload data which gets appended to a map storage.
 */
@Slf4j
public class AppendOnlyDataStoreService {
    @Getter
    private final List<MapStoreService<? extends PersistableNetworkPayloadStore<? extends PersistableNetworkPayload>, PersistableNetworkPayload>> services = new ArrayList<>();


    ///////////////////////////////////////////////////////////////////////////////////////////
    // Constructor
    ///////////////////////////////////////////////////////////////////////////////////////////

    @Inject
    public AppendOnlyDataStoreService() {
    }

    public void addService(MapStoreService<? extends PersistableNetworkPayloadStore<? extends PersistableNetworkPayload>, PersistableNetworkPayload> service) {
        services.add(service);
    }

    public void readFromResources(String postFix, Runnable completeHandler) {
        if (services.isEmpty()) {
            completeHandler.run();
            return;
        }
        AtomicInteger remaining = new AtomicInteger(services.size());
        services.forEach(service -> {
            service.readFromResources(postFix, () -> {
                if (remaining.decrementAndGet() == 0) {
                    completeHandler.run();
                }
            });
        });
    }

    // Uses synchronous execution on the userThread. Only used by tests. The async methods should be used by app code.
    @VisibleForTesting
    public void readFromResourcesSync(String postFix) {
        services.forEach(service -> service.readFromResourcesSync(postFix));
    }

    public Map<P2PDataStorage.ByteArray, PersistableNetworkPayload> getMap(PersistableNetworkPayload payload) {
        return services.stream()
                .filter(service -> service.canHandle(payload))
                .map(service -> {
                    Map<P2PDataStorage.ByteArray, PersistableNetworkPayload> map = service instanceof HistoricalDataStoreService ?
                            ((HistoricalDataStoreService) service).getMapOfAllData() :
                            service.getMap();
                    return map;
                })
                .findAny()
                .orElse(new HashMap<>());
    }

    public Map<P2PDataStorage.ByteArray, PersistableNetworkPayload> getMap() {
        return services.stream()
                .flatMap(service -> {
                    Map<P2PDataStorage.ByteArray, PersistableNetworkPayload> map = service instanceof HistoricalDataStoreService ?
                            ((HistoricalDataStoreService) service).getMapOfAllData() :
                            service.getMap();
                    return map.entrySet().stream();
                })
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    public boolean put(P2PDataStorage.ByteArray hashAsByteArray, PersistableNetworkPayload payload) {
        AtomicBoolean canHandle = new AtomicBoolean(false);
        services.stream()
                .filter(service -> {
                    canHandle.set(service.canHandle(payload));
                    return canHandle.get();
                })
                .forEach(service -> service.putIfAbsent(hashAsByteArray, payload));
        return canHandle.get();
    }
}

@@ -1044,39 +1044,16 @@
 til.
-concurrent.atomic.AtomicBoolean
+Optional
 ;%0Aim
@@ -1103,44 +1103,8 @@
 ger;
-%0Aimport java.util.stream.Collectors;
 %0A%0Aim
@@ -1158,16 +1158,59 @@
 Slf4j;%0A%0A
+import org.jetbrains.annotations.NotNull;%0A%0A
 /**%0A * U
@@ -2905,77 +2905,18 @@
 urn 
-services.stream()%0A                .filter(service -%3E service.canHandl
+findServic
 e(pa
@@ -2921,17 +2921,16 @@
 payload)
-)
 %0A       
@@ -2957,93 +2957,8 @@
 e -%3E
- %7B%0A                    Map%3CP2PDataStorage.ByteArray, PersistableNetworkPayload%3E map =
  ser
@@ -3018,36 +3018,32 @@
                 
-   
- 
 ((HistoricalData
@@ -3046,32 +3046,35 @@
 DataStoreService
+%3C?%3E
 ) service).getMa
@@ -3104,36 +3104,32 @@
                 
-    
 service.getMap()
@@ -3132,86 +3132,8 @@
 ap()
-;%0A                    return map;%0A                %7D)%0A                .findAny(
 )%0A  
@@ -3182,36 +3182,44 @@
   %7D%0A%0A    public 
-Map%3C
+boolean put(
 P2PDataStorage.B
@@ -3218,32 +3218,48 @@
 torage.ByteArray
+ hashAsByteArray
 , PersistableNet
@@ -3269,25 +3269,24 @@
 kPayload
-%3E getMap(
+ payload
 ) %7B%0A    
@@ -3293,349 +3293,281 @@
     
-return services.stream()%0A                .flatMap(service -%3E %7B%0A                    Map%3CP2PDataStorage.ByteArray, PersistableNetworkPayload%3E map = service instanceof HistoricalDataStoreService ?%0A                            ((HistoricalDataStoreService) service).getMapOfAllData() :%0A                            service.getMap();%0A      
+Optional%3CMapStoreService%3C? extends PersistableNetworkPayloadStore%3C? extends PersistableNetworkPayload%3E, PersistableNetworkPayload%3E%3E optionalService = findService(payload);%0A        optionalService.ifPresent(service -%3E service.putIfAbsent(hashAsByteArray, payload));%0A
         
     
@@ -3566,325 +3566,284 @@
     
-      
 return 
-map.entrySet().stream();%0A                %7D)%0A                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));%0A    %7D%0A%0A    public boolean put(P2PDataStorage.ByteArray hashAsByteArray, PersistableNetworkPayload payload) %7B%0A        AtomicBoolean canHandle = new AtomicBoolean(false);%0A
+optionalService.isPresent();%0A    %7D%0A%0A    @NotNull%0A    private Optional%3CMapStoreService%3C? extends PersistableNetworkPayloadStore%3C? extends PersistableNetworkPayload%3E, PersistableNetworkPayload%3E%3E findService(%0A            PersistableNetworkPayload payload) %7B%0A 
        
+return
  ser
@@ -3896,248 +3896,60 @@
  -%3E 
-%7B%0A                    canHandle.set(service.canHandle(payload));%0A                    return canHandle.get();%0A                %7D)%0A                .forEach(service -%3E service.putIfAbsent(hashAsByteArray, payload));%0A        return canHandle.get
+service.canHandle(payload))%0A                .findAny
 ();%0A

Refactor service filtering