/*
 * Copyright 2011 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.artifactcache;

import org.apache.ivy.core.IvyPatternHelper;
import org.apache.ivy.core.module.descriptor.Artifact;
import org.apache.ivy.core.module.descriptor.DefaultArtifact;
import org.apache.ivy.core.module.id.ArtifactRevisionId;
import org.gradle.api.internal.artifacts.ivyservice.ArtifactCacheMetaData;
import org.gradle.api.internal.artifacts.ivyservice.CacheLockingManager;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ModuleVersionRepository;
import org.gradle.cache.PersistentIndexedCache;
import org.gradle.util.TimeProvider;

import java.io.File;
import java.io.Serializable;
import java.util.Date;

public class DefaultArtifactResolutionCache implements ArtifactResolutionCache {
    
    private final TimeProvider timeProvider;
    private final ArtifactCacheMetaData cacheMetadata;
    private final CacheLockingManager cacheLockingManager;
    private PersistentIndexedCache<RevisionKey, ArtifactResolutionCacheEntry> byRepositoryCache;

    public DefaultArtifactResolutionCache(ArtifactCacheMetaData cacheMetadata, TimeProvider timeProvider, CacheLockingManager cacheLockingManager) {
        this.timeProvider = timeProvider;
        this.cacheLockingManager = cacheLockingManager;
        this.cacheMetadata = cacheMetadata;
    }
    
    private PersistentIndexedCache<RevisionKey, ArtifactResolutionCacheEntry> getByRepositoryCache() {
        if (byRepositoryCache == null) {
            byRepositoryCache = initByRepositoryCache();
        }
        return byRepositoryCache;
    }

    private PersistentIndexedCache<RevisionKey, ArtifactResolutionCacheEntry> initByRepositoryCache() {
        File artifactResolutionCacheFile = new File(cacheMetadata.getCacheDir(), getByRepositoryFileName());
        return cacheLockingManager.createCache(artifactResolutionCacheFile, RevisionKey.class, ArtifactResolutionCacheEntry.class);
    }

    private String getByRepositoryFileName() {
        return "artifacts-by-repository.bin";
    }

    public CachedArtifactResolution getCachedArtifactResolution(ModuleVersionRepository repository, ArtifactRevisionId artifactId) {
         ArtifactResolutionCacheEntry artifactResolutionCacheEntry = getByRepositoryCache().get(createKey(repository, artifactId));
        if (artifactResolutionCacheEntry == null) {
            return null;
        }
        Date lastModified = artifactResolutionCacheEntry.artifactLastModifiedTimestamp < 0 ? null : new Date(artifactResolutionCacheEntry.artifactLastModifiedTimestamp);
        return new DefaultCachedArtifactResolution(artifactId, artifactResolutionCacheEntry, timeProvider, lastModified);
    }

    public File storeArtifactFile(ModuleVersionRepository repository, ArtifactRevisionId artifactId, File artifactFile, Date lastModified) {
        getByRepositoryCache().put(createKey(repository, artifactId), createEntry(artifactFile, lastModified));
        return artifactFile;
    }

    public void expireCachedArtifactResolution(ModuleVersionRepository repository, ArtifactRevisionId artifact) {
        getByRepositoryCache().remove(createKey(repository, artifact));
    }

    private RevisionKey createKey(ModuleVersionRepository repository, ArtifactRevisionId artifactId) {
        String artifactPath = getArtifactKey(artifactId);
        return new RevisionKey(repository, artifactPath);
    }

    private String getArtifactKey(ArtifactRevisionId artifactId) {
        String format = "[organisation]/[module](/[branch])/[revision]/[type]/[artifact](-[classifier])(.[ext])";
        Artifact dummyArtifact = new DefaultArtifact(artifactId, null, null, false);
        return IvyPatternHelper.substitute(format, dummyArtifact);
    }

    private ArtifactResolutionCacheEntry createEntry(File artifactFile, Date lastModified) {
        return new ArtifactResolutionCacheEntry(artifactFile, timeProvider, lastModified == null ? -1 : lastModified.getTime());
    }

    private static class RevisionKey implements Serializable {
        private final String resolverId;
        private final String artifactId;

        private RevisionKey(ModuleVersionRepository repository, String artifactPath) {
            this.resolverId = repository.getId();
            this.artifactId = artifactPath;
        }

        @Override
        public String toString() {
            return resolverId + ":" + artifactId;
        }

        @Override
        public boolean equals(Object o) {
            if (o == null || !(o instanceof RevisionKey)) {
                return false;
            }
            RevisionKey other = (RevisionKey) o;
            return toString().equals(other.toString());
        }

        @Override
        public int hashCode() {
            return toString().hashCode();
        }
    }

}

@@ -1569,32 +1569,44 @@
 ndexedCache%3C
-Revision
+ArtifactAtRepository
 Key, Artifac
@@ -1981,32 +1981,44 @@
 ndexedCache%3C
-Revision
+ArtifactAtRepository
 Key, Artifac
@@ -2249,24 +2249,36 @@
 edCache%3C
-Revision
+ArtifactAtRepository
 Key, Art
@@ -2515,24 +2515,36 @@
 heFile, 
-Revision
+ArtifactAtRepository
 Key.clas
@@ -3835,24 +3835,36 @@
 private 
-Revision
+ArtifactAtRepository
 Key crea
@@ -4015,24 +4015,36 @@
 urn new 
-Revision
+ArtifactAtRepository
 Key(repo
@@ -4667,24 +4667,36 @@
 c class 
-Revision
+ArtifactAtRepository
 Key impl
@@ -4816,24 +4816,36 @@
 private 
-Revision
+ArtifactAtRepository
 Key(Modu
@@ -5222,24 +5222,36 @@
 tanceof 
-Revision
+ArtifactAtRepository
 Key)) %7B%0A
@@ -5310,37 +5310,61 @@
     
-RevisionKey other = (Revision
+ArtifactAtRepositoryKey other = (ArtifactAtRepository
 Key)

Rename class to more accurately reflect its purpose