package io.mattw.youtube.commentsuite;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.mattw.youtube.commentsuite.db.YouTubeObject;
import javafx.scene.image.Image;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * Cache for images and letter avatars.
 *
 * @author mattwright324
 */
public interface ImageCache {

    Logger logger = LogManager.getLogger();

    Cache<Object, Image> thumbCache = CacheBuilder.newBuilder()
            .maximumSize(500)
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .build();

    static Image toLetterAvatar(YouTubeObject object) {
        return toLetterAvatar(object.getTitle());
    }

    static Image toLetterAvatar(String s) {
        if (s == null || s.isEmpty()) {
            return toLetterAvatar(" ");
        } else {
            return toLetterAvatar(s.charAt(0));
        }
    }

    static Image toLetterAvatar(char letter) {
        Image image = thumbCache.getIfPresent(letter);
        if (image == null) {
            image = new LetterAvatar(letter);
            thumbCache.put(letter, image);
        }
        return image;
    }

    static Image findOrGetImage(String id, String imageUrl) {
        ConfigFile<ConfigData> config = FXMLSuite.getConfig();
        ConfigData configData = config.getDataObject();

        Image image = thumbCache.getIfPresent(id);
        if (image == null) {
            String fileFormat = "jpg";
            File thumbFile = new File(String.format("./thumbs/%s.%s", id, fileFormat));
            if (configData.getArchiveThumbs() && !thumbFile.exists()) {
                logger.debug("Archiving [id={}]", id);
                try {
                    thumbFile.mkdirs();
                    thumbFile.createNewFile();
                    ImageIO.write(ImageIO.read(new URL(imageUrl)), fileFormat, thumbFile);
                } catch (IOException e) {
                    logger.error("Failed to archive image.", e);
                }
            }
            if (thumbFile.exists()) {
                image = new Image(String.format("file:///%s", thumbFile.getAbsolutePath()));
            } else {
                image = new Image(imageUrl);
            }
            thumbCache.put(id, image);
        }
        return image;
    }

    static Image findOrGetImage(YouTubeObject object) {
        return findOrGetImage(object.getId(), object.getThumbUrl());
    }

    static Image findOrGetImage(YouTubeAccount account) {
        return findOrGetImage(account.getChannelId(), account.getThumbUrl());
    }

    static boolean hasImageCached(YouTubeObject object) {
        return thumbCache.getIfPresent(object.getId()) != null;
    }
}

@@ -319,16 +319,53 @@
 mageIO;%0A
+import java.awt.image.BufferedImage;%0A
 import j
@@ -613,24 +613,99 @@
 tLogger();%0A%0A
+    File thumbsDir = new File(%22thumbs/%22);%0A    String thumbFormat = %22jpg%22;%0A%0A
     Cache%3COb
@@ -1705,47 +1705,8 @@
 ) %7B%0A
-            String fileFormat = %22jpg%22;%0A
     
@@ -1739,16 +1739,27 @@
 ew File(
+thumbsDir, 
 String.f
@@ -1769,17 +1769,8 @@
 at(%22
-./thumbs/
 %25s.%25
@@ -1777,20 +1777,21 @@
 s%22, id, 
-file
+thumb
 Format))
@@ -1856,32 +1856,68 @@
 ile.exists()) %7B%0A
+                thumbsDir.mkdir();%0A%0A
                 
@@ -2001,28 +2001,72 @@
     
-thumbFile.mkdirs(
+BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl)
 );%0A
+%0A
     
@@ -2104,24 +2104,25 @@
 eNewFile();%0A
+%0A
             
@@ -2147,45 +2147,28 @@
 ite(
-ImageIO.read(new URL(imageUrl)), file
+bufferedImage, thumb
 Form
@@ -2286,10 +2286,21 @@
 mage
-.%22
+ %5Bid=%7B%7D%5D%22, id
 , e)
@@ -2536,32 +2536,72 @@
 ;%0A            %7D%0A
+%0A            if(!image.isError()) %7B%0A    
             thum
@@ -2615,32 +2615,46 @@
 put(id, image);%0A
+            %7D%0A
         %7D%0A      

Fix some thumb caching behavior for archival and varied internet status