package yukihane.inqubus.thumbnail;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.imageio.ImageIO;
import nicobrowser.NicoHttpClient;
import nicobrowser.util.RssContent;
import nicobrowser.util.RssContentParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import saccubus.worker.profile.ProxyProfile;

/**
 *
 * @author yuki
 */
public class Repository {

    private static final Logger logger = LoggerFactory.getLogger(Repository.class);
    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private final Map<String, Thumbnail> thumbnailMap = new HashMap<>();

    public void request(ProxyProfile proxy, File tempDir, String videoId) {
        synchronized (thumbnailMap) {
            final Thumbnail value = thumbnailMap.get(videoId);
            if (value != null) {
                return;
            }
        }

        executorService.execute(new ThumnailFetchWorker(proxy, tempDir, videoId));
    }

    public Thumbnail getThumnail(String videoId) {
        synchronized (thumbnailMap) {
            return thumbnailMap.get(videoId);
        }
    }

    private class ThumnailFetchWorker implements Runnable {

        private final ProxyProfile proxy;
        private final String videoId;
        private final File tempDir;

        private ThumnailFetchWorker(ProxyProfile proxy, File tempDir, String videoId) {
            this.proxy = proxy;
            this.videoId = videoId;
            this.tempDir = tempDir;
        }

        @Override
        public void run() {
            work();
        }

        private void work() {
            final NicoHttpClient client = createClient(proxy);

            try (InputStream is = client.getThumbInfo(videoId)) {
                final RssContent cont = new RssContentParser().parse(is);
                final URL thumbUrl = new URL(cont.getThumbnail_url());

                final File imageFile;
                try (InputStream imageStream = client.get(thumbUrl)) {
                    final BufferedImage image = ImageIO.read(imageStream);
                    imageFile = File.createTempFile("thumb", ".jpg", tempDir);
                    imageFile.deleteOnExit();
                    ImageIO.write(image, "jpeg", imageFile);
                }
                final Thumbnail thumb = new Thumbnail(cont.getTitle(), cont.getLength(), imageFile);

                synchronized (thumbnailMap) {
                    thumbnailMap.put(videoId, thumb);
                }
            } catch (IOException ex) {
                logger.error(null, ex);
            }
        }

        private NicoHttpClient createClient(ProxyProfile proxy) {
            if (proxy.use()) {
                return new NicoHttpClient(proxy.getHost(), proxy.getPort());
            } else {
                return new NicoHttpClient();
            }
        }
    }
}
