using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Postall.Domain.Services.Contracts;
using Postall.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Postall.Controllers
{
[Authorize]
public class VideosController : Controller
{
private readonly IVideoService _videoService;
private readonly IChannelService _channelService;
public VideosController(IVideoService videoService, IChannelService channelService)
{
_videoService = videoService;
_channelService = channelService;
}
///
/// Exibe a página principal com os vídeos organizados por canal
///
public async Task Index()
{
try
{
// Obtém os canais do usuário
var userChannelsResult = await _channelService.GetUserChannelsAsync();
if (!userChannelsResult.IsSuccess || !userChannelsResult.Value.Any())
{
return View(new List());
}
var channelsWithVideos = new List();
// Para cada canal, obtém os vídeos associados
foreach (var channel in userChannelsResult.Value)
{
var channelVideosResult = await _videoService.GetVideosByChannelIdAsync(channel.ChannelId);
var channelVideos = new ChannelVideosViewModel
{
Channel = channel,
Videos = channelVideosResult.IsSuccess
? channelVideosResult.Value.Select(v => new VideoViewModel
{
Id = v.Id,
VideoId = v.VideoId,
ChannelId = v.ChannelId,
Title = v.Title,
Description = v.Description,
ThumbnailUrl = v.ThumbnailUrl,
PublishedAt = v.PublishedAt,
ViewCount = v.ViewCount,
LikeCount = v.LikeCount,
DislikeCount = v.DislikeCount,
CommentCount = v.CommentCount
}).ToList()
: new List()
};
channelsWithVideos.Add(channelVideos);
}
return View(channelsWithVideos);
}
catch (Exception ex)
{
TempData["Error"] = $"Erro ao carregar vídeos: {ex.Message}";
return View(new List());
}
}
///
/// Exibe os vídeos disponíveis de um canal para serem adicionados
///
[HttpGet]
public async Task GetChannelVideos(string channelId)
{
try
{
var channelVideosResult = await _videoService.GetChannelVideosFromYouTubeAsync(channelId);
if (!channelVideosResult.IsSuccess)
{
return PartialView("_ChannelVideos", new List());
}
var videosViewModel = channelVideosResult.Value.Select(v => new VideoViewModel
{
Id = v.Id,
VideoId = v.VideoId,
ChannelId = v.ChannelId,
Title = v.Title,
Description = v.Description,
ThumbnailUrl = v.ThumbnailUrl,
PublishedAt = v.PublishedAt,
ViewCount = v.ViewCount,
LikeCount = v.LikeCount,
DislikeCount = v.DislikeCount,
CommentCount = v.CommentCount
}).ToList();
return PartialView("_ChannelVideos", videosViewModel);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
///
/// Adiciona vários vídeos à lista do usuário
///
[HttpPost]
public async Task AddVideos(string channelId, List selectedVideos)
{
if (string.IsNullOrEmpty(channelId))
{
TempData["Error"] = "ID do canal é obrigatório";
return RedirectToAction("Index");
}
if (selectedVideos == null || !selectedVideos.Any())
{
TempData["Error"] = "Selecione pelo menos um vídeo para adicionar";
return RedirectToAction("Index");
}
try
{
var result = await _videoService.AddVideosAsync(selectedVideos, channelId);
if (result.IsSuccess)
{
TempData["Message"] = "Vídeos adicionados com sucesso!";
}
else
{
TempData["Error"] = $"Erro ao adicionar vídeos: {result.Error.Description}";
}
}
catch (Exception ex)
{
TempData["Error"] = $"Erro ao adicionar vídeos: {ex.Message}";
}
return RedirectToAction("Index");
}
///
/// Remove um vídeo da lista do usuário
///
[HttpPost]
public async Task Remove(string id, string channelId)
{
if (string.IsNullOrEmpty(id))
{
TempData["Error"] = "ID do vídeo é obrigatório";
return RedirectToAction("Index");
}
try
{
var result = await _videoService.RemoveVideoAsync(id);
if (result.IsSuccess)
{
TempData["Message"] = "Vídeo removido com sucesso!";
}
else
{
TempData["Error"] = $"Erro ao remover vídeo: {result.Error.Description}";
}
}
catch (Exception ex)
{
TempData["Error"] = $"Erro ao remover vídeo: {ex.Message}";
}
return RedirectToAction("Index");
}
///
/// Busca vídeos no YouTube
///
[HttpGet]
public async Task Search(string query, string channelId)
{
if (string.IsNullOrEmpty(query) || query.Length < 3)
{
return Json(new { success = false, message = "A consulta deve ter pelo menos 3 caracteres" });
}
try
{
var results = await _videoService.SearchVideosAsync(query);
if (results.IsSuccess)
{
var videosViewModel = results.Value.Select(v => new VideoViewModel
{
VideoId = v.VideoId,
ChannelId = channelId, // Usado para saber a qual canal adicionar
Title = v.Title,
Description = v.Description,
ThumbnailUrl = v.ThumbnailUrl,
PublishedAt = v.PublishedAt,
ViewCount = v.ViewCount,
LikeCount = v.LikeCount,
DislikeCount = v.DislikeCount,
CommentCount = v.CommentCount
}).ToList();
return Json(new { success = true, data = videosViewModel });
}
return Json(new { success = false, message = "Erro ao buscar vídeos" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
}
}