using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using YTManager;
using YTManager.Models;
using Hangfire.Storage;

namespace YTManager.Controllers {
    [Produces("application/json")]
    [Route("api/Admin")]
    public class AdminController : Controller {
        // POST api/Admin/refreshytvids
        // Force a general youtube channel update.
        [HttpPost("job_update")]
        public void Post_forcejobupdate() {
            Hangfire.RecurringJob.Trigger(Startup.periodicupdatejobID);
        }

        // POST api/Admin/job_periodicupdate/YTChannelID
        // Force a YT Channel update.
        [HttpPost("job_update/{id}")]
        public void Post_forcejobupdateID([FromRoute] string id) {
            Hangfire.BackgroundJob.Enqueue(() => YTManager.Tasks.FetchVideos.run(id));
        }

        // POST api/Admin/job_periodicupdate
        // Ensures that the background YT Channel update API is running.
        [HttpPost("job_periodicupdate")]
        public void Post_periodicupdatejob() {
            Hangfire.RecurringJob.AddOrUpdate(
                Startup.periodicupdatejobID,
                () => YTManager.Tasks.FetchVideos.run(""),
                Hangfire.Cron.Hourly);
        }

        // GET api/Admin/job_periodicupdate
        // Check if the periodic update job is enqued.
        [HttpGet("job_periodicupdate")]
        public IActionResult Get_periodicupdatejob() {
            bool exists =  Hangfire.JobStorage.Current.GetConnection().GetRecurringJobs().Count(j => j.Id == Startup.periodicupdatejobID) > 0;
            return Ok(exists ? "true" : "false");
        }
    }
}