using InfluxDB.Client;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Domain.Settings;

namespace PARR.DAL.InfluxDbServices
{
    internal class InfluxDbService : IInfluxDbService
    {
        private readonly InfluxDbSettings settings;
        private readonly ILogger<InfluxDbService> logger;

        public InfluxDbService(InfluxDbSettings settings, ILogger<InfluxDbService> logger)
        {
            this.settings = settings;
            this.logger = logger;
        }

        public bool Write(Action<WriteApi> action, string token)
        {
            try
            {
                using var client = new InfluxDBClient(settings.Url, token);
                using (var write = client.GetWriteApi())
                {
                    action(write);
                }

                return true;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Ошибка при записи в БД, InfluxDb");
                return false;
            }
        }

        public async Task<T> QueryAsync<T>(Func<QueryApi, Task<T>> action, string token)
        {
            try
            {
                using var client = new InfluxDBClient(settings.Url, token);
                var query = client.GetQueryApi();

                return await action(query);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Ошибка при запросе данных из БД, InfuxDb");
                // return  Task.FromResult();
                // return Task.CompletedTask;
                //return default(T);
                return default(T);
            }
        }
    }
}
