package com.example.video_downloader.services;

import com.example.video_downloader.entity.StatusEnum;
import com.example.video_downloader.entity.Video;
import com.example.video_downloader.repositories.VideoRepository;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class ProcessService {

    @Autowired
    private VideoRepository videoRepository;

    @PostConstruct
    public void validateVideos() throws IOException, InterruptedException {
        List<Video> response = videoRepository.findUrlByStatus(StatusEnum.NEW);
        for(Video video : response) {
            if(video.getStatus().equals(StatusEnum.NEW)){
                downloadVideo(video.getUrl());
                video.setStatus(StatusEnum.SAVED);
                videoRepository.save(video);
            } else {
                return;
            }
        }
    }

    //@PostConstruct
    public void downloadVideo(String url) throws InterruptedException, IOException {
        try {
            execute("yt-dlp", "youtube:player_client=android", url);
        } catch (Exception e) {
            System.out.println("Something went awry.");
        }

    }

    public void execute(String... command) throws InterruptedException, IOException {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectError(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        process.waitFor();
    }


}
