package com.itdominator.api.util;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.RequiredArgsConstructor;



@Component
@RequiredArgsConstructor
public class Thumbnailer {

    @Value("${videos.filter}")
    private final String[] videoFilter;

    public Set<Path> collectVideoFilePaths(final String dir) throws IOException {
        Set<Path> paths = new HashSet<>();

        DirectoryStream<Path> stream = Files.newDirectoryStream( Paths.get(dir) );
        for (Path path : stream) {
            if ( !Files.isDirectory(path) ) {
                String target = path.getFileName().toString();
                for (String filterItem : videoFilter) {
                    if ( target.endsWith(filterItem) ) {
                        paths.add(path);
                    }
                }
            }
        }

        return paths;
    }

    public void generateThumbnails(Set<Path> paths) throws IOException {
        for (Path path : paths) {
            String fileName = path.getFileName().toString();
            String fileHash = DigestUtils.sha256Hex(fileName);
            generateThumbnail(path.toString(), "/tmp/" + fileHash + ".jpg","65%");
        }
    }

    // proc = subprocess.Popen([self.FFMPG_THUMBNLR, "-t", scrub_percent, "-s", "300", "-c", "jpg", "-i", full_path, "-o", hash_img_path])
    private void generateThumbnail(final String full_path, final String hash_img_path, final String scrub_percent) throws IOException {
        ProcessBuilder pb = new ProcessBuilder("ffmpegthumbnailer", "-t", scrub_percent, "-s", "300", "-c", "jpg", "-i", full_path, "-o", hash_img_path);
        Process p = pb.start();
        while (p.isAlive()) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
