using System.Threading.Tasks;
using System.Windows.Forms;
using PolyTraderSharp.Models;
using PolyTraderSharp.Services;

namespace PolyTraderSharp.Ui.Views
{
    /// <summary>
    /// Ansicht der Hintergrund-Jobs (JobManager). Designbar (JobsView.Designer.cs).
    /// Verhalten wie der bisherige Jobs-Tab: „Run Now" löst den ManualTrigger aus,
    /// „Aktiv" schaltet den Job über die Bindung.
    /// </summary>
    public partial class JobsView : Form
    {
        public JobsView()
        {
            InitializeComponent();
            colLastRun.DefaultCellStyle.Format = "HH:mm:ss";
            colNextRun.DefaultCellStyle.Format = "HH:mm:ss";
            dgvJobs.CellContentClick += DgvJobs_CellContentClick;
            tsJobsRefresh.Click += (_, _) => dgvJobs.Refresh();
        }

        public void Initialize(JobManager jobManager)
        {
            dgvJobs.DataSource = new System.ComponentModel.BindingList<JobStatusRow>(jobManager.Jobs);
        }

        private void DgvJobs_CellContentClick(object? sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var dgv = (DataGridView)sender!;
            var colName = dgv.Columns[e.ColumnIndex].Name;

            if (dgv.Rows[e.RowIndex].DataBoundItem is JobStatusRow job)
            {
                if (colName == "col_dgv_jobs_Run")
                {
                    if (job.ManualTriggerAction != null)
                        _ = Task.Run(() => job.ManualTriggerAction.Invoke());
                }
                else if (colName == "col_dgv_jobs_Enabled")
                {
                    dgv.EndEdit();
                }
            }
        }
    }
}
