package com.example.video_downloader.services;

import com.example.video_downloader.entity.Playlist;
import com.example.video_downloader.entity.StatusEnum;
import com.example.video_downloader.entity.Video;
import com.example.video_downloader.repositories.PlaylistRepository;
import com.example.video_downloader.repositories.VideoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
public class YTDLPService {

    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private PlaylistService playlistService;

    @Autowired
    private PlaylistRepository playlistRepository;

    @Autowired
    private ProcessService processService;


    public void processPlaylist() throws IOException, InterruptedException {
        List<Playlist> playlists = playlistRepository.findByStatus(StatusEnum.NEW);

        for(Playlist playlist : playlists) {
            String urls =  processService.execute("yt-dlp", "--flat-playlist", "--print", "webpage_url", playlist.getUrl());
            for(String url : urls.split("\\n")){
                Video video = new Video();
                video.setUrl(url);
                video.setStatus(StatusEnum.NEW);
                video.getPlaylist().add(playlist);
                videoRepository.save(video);
            }

        }

    }

    public void validateVideos() throws HttpClientErrorException, IOException, InterruptedException {
        List<Video> response = videoRepository.findByStatus(StatusEnum.NEW);

        for(Video video : response) {
                downloadVideo(video.getUrl(), video.getId());
                Path filePath = Paths.get("downloads/" + video.getId() + ".webm");
                if(Files.exists(filePath) && Files.isRegularFile(filePath)) {
                    System.out.println("Apparently it exists mate.");
                    video.setFullPath(String.valueOf(filePath));
                    video.setStatus(StatusEnum.SAVED);
                } else {
                    System.out.println("Download failed.");
                    video.setStatus(StatusEnum.FAILED);
                }
                videoRepository.save(video);

        }
    }

    public void downloadVideo(String url, Long id) throws HttpClientErrorException, InterruptedException, IOException {
        String outputPath = "downloads/" + id + ".%(ext)s";
        String result = processService.execute("yt-dlp", "--print", "%(title)s, %(uploader)s, %(upload_date)s, %(duration_string)s", outputPath, url);
        System.out.println(result);
    }


}
