using Microsoft.AspNetCore.Mvc;
using PhilExampleCrawler.Common.Models;
using PhilExampleCrawler.Core;
using PhilExampleCrawler.DataBase;
using PhilExampleCrawler.DataBase.Models;
using WebAPI.Interfaces;
using System.Linq;

namespace WebAPI.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class CrawlSessionController : ControllerBase
    {
        private readonly ILogger<CrawlSessionController> _logger;

        private readonly ICrawlScheduler<List<Insertion>> _scheduler;
        private readonly HttpClient _httpClient;

        public CrawlSessionController(ILogger<CrawlSessionController> logger,
                                      ICrawlScheduler<List<Insertion>> scheduler,
                                      IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _scheduler = scheduler;
            _httpClient = httpClientFactory.CreateClient();
        }


        [HttpGet]
        public async Task<IEnumerable<CrawlSession>?> GetCrawlSessionsAsync(int userID)
        {
            if (userID < 1)
                return null;

            var user = await ThreadSafeCache.GetUserAsync(userID);
            return user?.CrawlSessions;
        }

        [HttpGet]
        public async Task<IEnumerable<Insertion>?> GetLatestInsertionAsync(int userID, int? limit)
        {
            if (userID < 1)
                return null;

            var ins = await ThreadSafeCache.GetInsertions(userID, limit ?? 5);
            return ins;
        }

        [HttpPost]
        public async Task<CrawlSession?> RegisterCrawlSessionAsync(int userID, CrawlSession cs)
        {
            if (userID < 1)
                return null;

            CrawlSession? sess = await ThreadSafeCache.AddCrawlSessionAsync(userID, cs);
            if (sess != null)
                _scheduler.AddTask(sess.ID, new BaseCrawler_Best(sess, _httpClient).CrawlAsync);

            return sess;
        }

        [HttpPost]
        public async Task<bool> UpdateCrawlSessionAsync(int userID, CrawlSession cs)
        {
            if (userID < 1)
                return false;

            bool updated = await ThreadSafeCache.UpdateCrawlSessionAsync(userID, cs);
            return updated;
        }

        [HttpDelete]
        public async Task<bool> DeleteCrawlSessionAsync(int crawlSessionID)
        {
            if (crawlSessionID < 1)
                return false;

            bool deleted = await ThreadSafeCache.RemoveCrawlSessionAsync(crawlSessionID);
            _scheduler.RemoveTask(crawlSessionID);
            return deleted;
        }


    }
}