/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.api.internal.artifacts.ivyservice.resolveengine.store;

import org.gradle.api.internal.cache.Store;
import org.gradle.api.internal.file.TemporaryFileProvider;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.internal.CompositeStoppable;
import org.gradle.util.Clock;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ResolutionResultsStoreFactory implements Closeable {
    private final static Logger LOG = Logging.getLogger(ResolutionResultsStoreFactory.class);
    private static final int DEFAULT_MAX_SIZE = 2000000000; //2 gigs

    private final TemporaryFileProvider temp;
    private int maxSize;

    private CachedStoreFactory oldModelCache;
    private CachedStoreFactory newModelCache;

    public ResolutionResultsStoreFactory(TemporaryFileProvider temp) {
        this(temp, DEFAULT_MAX_SIZE);
    }

    /**
     * @param temp
     * @param maxSize - indicates the approx. maximum size of the binary store that will trigger rolling of the file
     */
    ResolutionResultsStoreFactory(TemporaryFileProvider temp, int maxSize) {
        this.temp = temp;
        this.maxSize = maxSize;
    }

    private final Map<String, DefaultBinaryStore> stores = new HashMap<String, DefaultBinaryStore>();
    private final CompositeStoppable cleanUpLater = new CompositeStoppable();

    public DefaultBinaryStore createBinaryStore(String id) {
        String storeKey = Thread.currentThread().getId() + id; //one store per thread
        DefaultBinaryStore store = stores.get(storeKey);
        if (store == null || isFull(store)) {
            File storeFile = temp.createTemporaryFile("gradle", ".bin");
            storeFile.deleteOnExit();
            store = new DefaultBinaryStore(storeFile);
            stores.put(storeKey, store);
            cleanUpLater.add(store);
        }
        return store;
    }

    //offset based implementation is only safe up to certain figure
    //because of the int max value
    //for large streams/files (huge builds), we need to roll the file
    //otherwise the stream.size() returns max integer and the offset is no longer correct
    private boolean isFull(DefaultBinaryStore store) {
        return store.getSize() > maxSize;
    }

    public void close() throws IOException {
        Clock clock = new Clock();
        cleanUpLater.stop();
        LOG.debug("Deleted {} resolution results binary files in {}", stores.size(), clock.getTime());
        oldModelCache = null;
        newModelCache = null;
        stores.clear();
    }

    public <T> Store<T> createOldModelCache(String id) {
        if (oldModelCache == null) {
            oldModelCache = new CachedStoreFactory("Resolution result");
            cleanUpLater.add(oldModelCache);
        }
        return oldModelCache.createCachedStore(id);
    }

    public <T> Store<T> createNewModelCache(String id) {
        if (newModelCache == null) {
            newModelCache = new CachedStoreFactory("Resolved configuration");
            cleanUpLater.add(newModelCache);
        }
        return newModelCache.createCachedStore(id);
    }
}
@@ -994,36 +994,8 @@
 le;%0A
-import java.io.IOException;%0A
 impo
@@ -2953,29 +2953,28 @@
 e() 
-throws IOException %7B%0A
+%7B%0A        try %7B%0A    
     
@@ -3004,32 +3004,36 @@
 lock();%0A        
+    
 cleanUpLater.sto
@@ -3033,24 +3033,28 @@
 ter.stop();%0A
+    
         LOG.
@@ -3144,16 +3144,40 @@
 ime());%0A
+        %7D finally %7B%0A    
         
@@ -3198,32 +3198,36 @@
 = null;%0A        
+   
+ 
 newModelCache = 
@@ -3224,32 +3224,36 @@
 elCache = null;%0A
+    
         stores.c
@@ -3256,24 +3256,34 @@
 es.clear();%0A
+        %7D%0A
     %7D%0A%0A    p

Discard state in a finally { } block.