package com.example.video_downloader.services;

import com.example.video_downloader.entity.Creator;
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.CreatorRepository;
import com.example.video_downloader.repositories.PlaylistRepository;
import com.example.video_downloader.repositories.VideoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 {

    Logger LOGGER = LoggerFactory.getLogger(YTDLPService.class);
    /* FIXME
     *  LOGGER.debug("Valami szoveg: {}", valtozo);
     *  LOGGER.warn("Valami szoveg: {}", valtozo);
     *  LOGGER.info("Valami szoveg: {}", valtozo);
     *  LOGGER.error("Valami szoveg: {}", valtozo);
     *  mindegyik ugyan ugy mukodik, csak a log levelt be lehet allitani propertykent es akkor ha mondjuk error a loglevel akkor a debug logokat nem irja ki csak ami errorkent van logolva
     *
     * */
    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private PlaylistService playlistService;

    @Autowired
    private PlaylistRepository playlistRepository;

    @Autowired
    private ProcessService processService;

    @Autowired
    private CreatorRepository creatorRepository;


    public void processPlaylist() throws IOException, InterruptedException {
        List<Playlist> playlists = playlistRepository.findByStatus(StatusEnum.NEW);
        for(Playlist playlist : playlists) {
            String urls =  processService.execute("yt-dlp", "--force-ipv4", "--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);
            }
            /* FIXME itt ugye fogod a playlistet es lemented az osszes hozza tartozo videot.
               Ha ezzel vegeztel, akkor a playlist-nek a statuszat at kene allitani NEW-rol, *valamire*
               Kene keresni valami elnevezest arra hogy "a playlistben levo videokat meg nem toltottem le, de az video entityket mar letrehoztam"
               Pl.: PROCESSED bar nem vagyok benne biztos hogy ez lenne a legjobb nev ra.
               Amit mondani akarok az az hogy ha ez a methodus lefutott, akkor ha ranezek a DB-re akkor nem tudom megkulonboztetni egy playlisten hogy csak most lett bekuldve,
               vs mar elkezdtuk feldolgozni, es lementeni a hozza tartozo videokat.
             * */

        }

    }

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

        for(Video video : response) {
                String data = processVideo(video.getUrl());
                String[] parts = data.trim().split(", ");
                    video.setName(parts[0]);
                    video.setUploadDate(parts[2]);
                    video.setDuration(parts[3]);

                    String creatorName = parts[1];
                    String creatorUrl = parts[4];

                    Creator creator = creatorRepository
                            .findByName(creatorName)
                            .orElseGet(() -> {
                                Creator newCreator = new Creator();
                                newCreator.setName(creatorName);
                                newCreator.setUrl(creatorUrl);
                                return creatorRepository.save(newCreator);
                            });
                    video.setCreator(creator);
                videoRepository.save(video);
        }
    }

    public void downloadVideos() throws 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 String processVideo(String url) throws HttpClientErrorException, InterruptedException, IOException {
        return processService.execute("yt-dlp", "--force-ipv4", "--skip-download", "--print", "%(title)s, %(uploader)s, %(upload_date)s, %(duration_string)s, %(uploader_url)s", url);
    }
    public void downloadVideo(String url, Long id) throws HttpClientErrorException, InterruptedException, IOException {
        String outputPath = "downloads/" + id + ".%(ext)s";
        String result = processService.execute("yt-dlp", "--force-ipv4", "-o", outputPath, url);
        System.out.println(result);
    }


}
