using System.Collections.Generic;
using CounterDrone.Core;
using CounterDrone.Core.Models;
using CounterDrone.Core.Services;
using UnityEngine;
using CounterDrone.Core.Simulation;

namespace CounterDrone.Unity
{
    public class ReportManager : MonoBehaviour
    {
        private IReportService _service;
        private IPathProvider _paths;
        private SQLite.SQLiteConnection _db;

        public IReportService Service => _service;

        public void Awake()
        {
            _paths = new UnityPathProvider();
            _db = new DatabaseManager(_paths).OpenMainDb();
            SqliteConnectionTracker.Track(_db);
            _service = new ReportService(_db, _paths);
        }

        void OnDisable() { SqliteConnectionTracker.Untrack(_db); _db?.Dispose(); _db = null; }

        public SimulationReport Generate(string taskId, TaskFullConfig cfg, List<SimEvent> events, string status, float duration)
            => _service.Generate(taskId, cfg, events, status, duration);

        public SimulationReport Get(string id) => _service.GetReport(id);
        public void Delete(string id) => _service.DeleteReport(id);
        public PagedResult<SimulationReport> Search(string kw, string from, string to, int page, int size)
            => _service.SearchReports(kw, from, to, page, size);

        public string Export(string reportId)
        {
            var dir = System.IO.Path.Combine(_paths.GetDataRoot(), "reports");
            return _service.ExportToFile(reportId, dir);
        }

        [ContextMenu("Verify")]
        void Verify()
        {
            Awake();
            Debug.Log($"ReportManager OK. Reports dir: {System.IO.Path.Combine(_paths.GetDataRoot(), "reports")}");
        }
    }
}
