using HtmlAgilityPack;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

[Route("api/[controller]")]
[ApiController]
public class RealEstateController : ControllerBase
{
    // Step 1: Find image links without downloading
    [HttpPost("findImages")]
    public async Task<IActionResult> FindImages([FromBody] UrlRequest request)
    {
        if (string.IsNullOrEmpty(request.Url))
        {
            return BadRequest("URL is required.");
        }

        try
        {
            var imageLinks = await FetchImageLinksFromWebsiteAsync(request.Url);
            return Ok(new { images = imageLinks });
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error: {ex.Message}");
        }
    }

    // Step 2: Download images when user chooses to do so
    [HttpPost("download")]
    public async Task<IActionResult> DownloadWebsite([FromBody] UrlRequest request)
    {
        if (string.IsNullOrEmpty(request.Url))
        {
            return BadRequest("URL is required.");
        }

        try
        {
            var images = await FetchImagesFromWebsiteAsync(request.Url);

            // Log the fetched images
            Console.WriteLine("Fetched images: " + string.Join(", ", images));

            return Ok(new { images });
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error: {ex.Message}");
        }
    }


    // Fetch just the image links
    private async Task<List<string>> FetchImageLinksFromWebsiteAsync(string url)
    {
        var imageLinks = new List<string>();
        var httpClient = new HttpClient();

        // Set User-Agent to imitate a browser request
        httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");

        try
        {
            // Send the GET request with headers
            var response = await httpClient.GetStringAsync(url);

            // Load the HTML into HtmlAgilityPack
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(response);

            // Select all <li> elements containing the images you want
            var liNodes = htmlDocument.DocumentNode.SelectNodes("//li[contains(@class, 'flex items-center justify-center')]");

            if (liNodes != null)
            {
                foreach (var liNode in liNodes)
                {
                    // Find the <img> tag within the <li> node
                    var imgNode = liNode.SelectSingleNode(".//img[contains(@class, 'absolute top-0 left-0 w-full h-full')]");

                    if (imgNode != null)
                    {
                        var imgSrc = imgNode.GetAttributeValue("src", "");

                        if (!string.IsNullOrEmpty(imgSrc))
                        {
                            // Ensure absolute URL if necessary
                            if (!Uri.IsWellFormedUriString(imgSrc, UriKind.Absolute))
                            {
                                var baseUri = new Uri(url);
                                imgSrc = new Uri(baseUri, imgSrc).ToString();
                            }

                            imageLinks.Add(imgSrc);
                        }
                    }
                }
            }
        }
        catch (HttpRequestException ex)
        {
            // Catch any network-related exceptions (403, 404, etc.)
            Console.WriteLine($"Error: {ex.Message}");
            throw new Exception($"Error fetching images: {ex.Message}");
        }

        return imageLinks;
    }



    // Fetch images and download
    private async Task<List<string>> FetchImagesFromWebsiteAsync(string url)
    {
        var images = new List<string>();
        var httpClient = new HttpClient();
        var response = await httpClient.GetStringAsync(url);

        // Load the HTML into HtmlAgilityPack
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(response);

        // Select all <img> elements with the specified class
        var imgNodes = htmlDocument.DocumentNode.SelectNodes("//li//img");

        if (imgNodes != null)
        {
            foreach (var imgNode in imgNodes)
            {
                var imgSrc = imgNode.GetAttributeValue("src", "");
                if (!string.IsNullOrEmpty(imgSrc))
                {
                    // Ensure absolute URL if necessary
                    if (!Uri.IsWellFormedUriString(imgSrc, UriKind.Absolute))
                    {
                        var baseUri = new Uri(url);
                        imgSrc = new Uri(baseUri, imgSrc).ToString();
                    }
                    images.Add(imgSrc);
                }
            }
        }

        return images;
    }

}

public class UrlRequest
{
    public string Url { get; set; }
}
