using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Percent___Qualification_work.Classes;
using System.Threading.Tasks;
using System.IO;

namespace Percent___Qualification_work.Classes
{
    internal class api_scrape_movie
    {
        private readonly string apiKey = "f4312a0a6d6e2b6222ab8bb313a3417d";
        public async Task<Movie> GetMovie(string movieTitle)
        {
            string baseUrl = "https://api.themoviedb.org/3";

            // Search for the movie to get its ID
            string searchUrl = $"{baseUrl}/search/movie?api_key={apiKey}&query={Uri.EscapeDataString(movieTitle)}";

            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    // Fetch search results
                    HttpResponseMessage searchResponse = await httpClient.GetAsync(searchUrl);
                    searchResponse.EnsureSuccessStatusCode();
                    string searchContent = await searchResponse.Content.ReadAsStringAsync();
                    var searchResults = JsonSerializer.Deserialize<JsonElement>(searchContent);

                    if (searchResults.GetProperty("results").GetArrayLength() == 0)
                        return null; // Return null if no results found

                    // Get the first movie ID from search results
                    int movieId = searchResults.GetProperty("results")[0].GetProperty("id").GetInt32();

                    // Fetch movie details
                    string movieDetailsUrl = $"{baseUrl}/movie/{movieId}?api_key={apiKey}&append_to_response=credits";
                    HttpResponseMessage movieDetailsResponse = await httpClient.GetAsync(movieDetailsUrl);
                    movieDetailsResponse.EnsureSuccessStatusCode();
                    string movieDetailsContent = await movieDetailsResponse.Content.ReadAsStringAsync();
                    var movieDetails = JsonSerializer.Deserialize<JsonElement>(movieDetailsContent);

                    // Extract relevant data
                    string title = movieDetails.GetProperty("title").GetString();
                    int releaseYear = DateTime.Parse(movieDetails.GetProperty("release_date").GetString()).Year;
                    string genre = movieDetails.GetProperty("genres").GetArrayLength() > 0
                        ? movieDetails.GetProperty("genres")[0].GetProperty("name").GetString()
                        : "Unknown";

                    // Get director from credits
                    string director = "Unknown";
                    if (movieDetails.GetProperty("credits").GetProperty("crew").GetArrayLength() > 0)
                    {
                        foreach (var crewMember in movieDetails.GetProperty("credits").GetProperty("crew").EnumerateArray())
                        {
                            if (crewMember.GetProperty("job").GetString() == "Director")
                            {
                                director = crewMember.GetProperty("name").GetString();
                                break;
                            }
                        }
                    }

                    // Fetch cover image as a blob
                    string posterPath = movieDetails.GetProperty("poster_path").GetString();
                    byte[] coverImage = await GetCoverImage(posterPath);
                    if (coverImage == null)
                    {
                        coverImage = ImageToByteArray(Properties.Resources.no_image);
                    }

                    // Return the Movie object
                    return new Movie(null, title, genre, director, releaseYear, coverImage);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception occurred: {ex.Message}");
                    return null;
                }
            }
        }

        // Method to fetch the movie's cover image as a byte array
        private async Task<byte[]> GetCoverImage(string posterPath)
        {
            if (string.IsNullOrEmpty(posterPath))
                return null;

            string imageUrl = $"https://image.tmdb.org/t/p/w500{posterPath}";

            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    return await httpClient.GetByteArrayAsync(imageUrl);
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
        byte[] ImageToByteArray(System.Drawing.Image image)
        {
            using (var ms = new MemoryStream())
            {
                image.Save(ms, image.RawFormat);
                return ms.ToArray();
            }
        }
    }
}
