package com.example.video_downloader.controllers;

import com.example.video_downloader.dto.SaveNewPlaylistRequest;
import com.example.video_downloader.dto.SaveNewVideoRequest;
import com.example.video_downloader.entity.Playlist;
import com.example.video_downloader.entity.Video;
import com.example.video_downloader.services.PlaylistService;
import com.example.video_downloader.services.VideoService;
import com.example.video_downloader.services.YTDLPService;
import lombok.Data;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping(path="/v2")
@CrossOrigin(origins = "http://localhost:3000")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private PlaylistService playlistService;

    @Autowired
    private YTDLPService ytdlpService;


    @Data
    private static class Trigger {
        private boolean input;
    }

    @PostMapping(path = "/videos")
    //https://www.baeldung.com/exception-handling-for-rest-with-spring
    //global exception handling

    public ResponseEntity saveNewVideo(@RequestBody SaveNewVideoRequest request){
        try {
            return ResponseEntity.ok(videoService.saveNewVideo(request));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping(path = "/playlists")
    public void saveNewPlaylist(@RequestBody SaveNewPlaylistRequest request){
        Playlist playlist = playlistService.saveNewPlaylist(request);

    }

    @GetMapping(path = "/all")
    public ResponseEntity<List<Video>> getAllVideos(){
        return ResponseEntity.ok(videoService.getVideos());
    }

    @GetMapping(path = "/{id}")
    public ResponseEntity<Video> getVideoById(@PathVariable Long id){
        return ResponseEntity.ok(videoService.getVideoById(id));

    }

    @PostMapping(path = "/fire")
    public int getJobDone(@RequestBody @NotNull Trigger trigger) throws IOException, InterruptedException {

        int statusCode = 200;
        if(trigger.input) {
            ytdlpService.processPlaylist();
            ytdlpService.validateVideos();
            ytdlpService.downloadVideos();
        }
        return statusCode;

    }
}
