package net.yeputons.ofeed.db;

import android.app.DownloadManager;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.j256.ormlite.dao.Dao;
import net.yeputons.ofeed.OfeedApplication;
import net.yeputons.ofeed.web.DownloadCompleteListener;
import net.yeputons.ofeed.web.ResourceDownload;
import net.yeputons.ofeed.web.ResourceDownloader;
import net.yeputons.ofeed.web.WebResource;
import net.yeputons.ofeed.web.dmanager.DownloadManagerResourceDownloader;

import java.io.File;
import java.net.URI;
import java.sql.SQLException;
import java.util.List;
import java.util.WeakHashMap;

public class WebResourcesCache {
    private static final String TAG = WebResourcesCache.class.getName();
    private static final WeakHashMap<URI, WebResource> inMemoryResources = new WeakHashMap<>();

    @NonNull
    private static synchronized WebResource getWebResource(@NonNull URI uri) {
        WebResource result = inMemoryResources.get(uri);
        if (result != null) {
            return result;
        }
        result = new WebResource(uri);
        File foundFile = null;
        try {
            Dao<CachedWebResource, Integer> dao = DbHelper.get().getCachedWebResourcesDao();
            List<CachedWebResource> foundList = dao.queryForEq(CachedWebResource.URI_FIELD, uri.toString());
            if (foundList.size() > 1) {
                Log.e(TAG, "Found more than one WebResource for an URI: " + uri);
            }
            while (!foundList.isEmpty()) {
                foundFile = new File(foundList.get(0).localFile);
                if (foundFile.canRead()) {
                    break;
                } else {
                    Log.w(TAG, "File disappeared from cache: " + foundFile.toString() + " for " + uri.toString());
                    foundFile = null;
                    dao.delete(foundList.get(0));
                }
            }
        } catch (SQLException e) {
            Log.e(TAG, "Error while retrieving WebResource from DB cache", e);
        }
        if (foundFile != null) {
            final CachedResourceDownload download = new CachedResourceDownload(foundFile);
            result.addDownload(new ResourceDownloader() {
                @NonNull
                @Override
                public ResourceDownload createDownload(@NonNull WebResource resource) {
                    return download;
                }
            });
        }
        inMemoryResources.put(uri, result);
        return result;
    }

    @Nullable
    public static WebResource getCachedDownloadingWebResource(@NonNull URI uri) {
        return inMemoryResources.get(uri);
    }

    @NonNull
    public static WebResource getDownloadingWebResource(@NonNull URI uri) {
        WebResource resource  = getWebResource(uri);
        ResourceDownload download = resource.getActualDownload();
        if (download != null) {
            if (download.getState() == ResourceDownload.State.NOT_STARTED) {
                download.start();
            } else if (download .getState() == ResourceDownload.State.FAILED) {
                download = null;
            }
        }
        if (download == null) {
            ResourceDownload d = resource.addDownload(OfeedApplication.getDownloader());
            d.start();
        }
        return resource;
    }
}

@@ -1537,35 +1537,50 @@
     
-while (!foundList.isEmpty()
+for (CachedWebResource attempt : foundList
 ) %7B%0A
@@ -1616,32 +1616,23 @@
 ew File(
-foundList.get(0)
+attempt
 .localFi
@@ -1919,24 +1919,15 @@
 ete(
-foundList.get(0)
+attempt
 );%0A 
@@ -2792,32 +2792,38 @@
  uri) %7B%0A        
+final 
 WebResource reso
@@ -3233,32 +3233,38 @@
 ) %7B%0A            
+final 
 ResourceDownload
@@ -3339,32 +3339,728 @@
      d.start();%0A
+            d.addDownloadCompleteListener(new DownloadCompleteListener() %7B%0A                @Override%0A                public void onDownloadComplete() %7B%0A                    Dao%3CCachedWebResource, Integer%3E dao = DbHelper.get().getCachedWebResourcesDao();%0A                    CachedWebResource r = new CachedWebResource();%0A                    r.uri = resource.uri.toString();%0A                    r.localFile = d.getLocalFile().getAbsolutePath();%0A                    try %7B%0A                        dao.create(r);%0A                    %7D catch (SQLException e) %7B%0A                        Log.e(TAG, %22Unable to save downloaded resource into db%22, e);%0A                    %7D%0A                %7D%0A            %7D);%0A
         %7D%0A      

make it cache downloaded files in DB; fix bug in DB loading logic