using Apache.IoTDB;
using Apache.IoTDB.DataStructure;
using JiShe.CollectBus.IoTDB.Interface;
using JiShe.CollectBus.IoTDB.Options;
using Microsoft.Extensions.Logging;

namespace JiShe.CollectBus.IoTDB.Provider
{
    /// <summary>
    /// 表模型Session连接池
    /// </summary>
    public class TableSessionPoolAdapter : IIoTDbSessionPool
    {
        private readonly TableSessionPool _sessionPool;
        private readonly IoTDbOptions _options;

        /// <summary>
        /// TableSessionPoolAdapter
        /// </summary>
        /// <param name="options"></param>
        public TableSessionPoolAdapter(IoTDbOptions options)
        {
            _options = options;
            _sessionPool = new TableSessionPool.Builder()
                .SetNodeUrls(options.ClusterList)
                .SetUsername(options.UserName)
                .SetPassword(options.Password)
                .SetZoneId(options.ZoneId)
                .SetFetchSize(options.FetchSize)
                .SetPoolSize(options.PoolSize)
                .SetDatabase(options.DataBaseName)
                .Build();
        }

        /// <summary>
        /// 打开连接池
        /// </summary>
        /// <returns></returns>
        public async Task OpenAsync()
        {
            await _sessionPool.Open(false);
            if (_options.OpenDebugMode)
            {
                _sessionPool.OpenDebugMode(builder => builder.AddConsole());
            }
        }

        /// <summary>
        /// 关闭连接池
        /// </summary>
        /// <returns></returns>
        public async Task CloseAsync()
        {
            if (_sessionPool == null)
            {
                return;
            }
            await _sessionPool.Close();
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="tablet"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(Tablet tablet)
        {
            var result = await _sessionPool.InsertAsync(tablet);
            if (result != 0)
            {
                throw new Exception($"{nameof(TableSessionPoolAdapter)} table模型数据入库没有成功，返回结果为：{result}，请检查IoTEntity继承子类属性索引是否有变动。");
            }

            //await CloseAsync();
            return result;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<SessionDataSet> ExecuteQueryStatementAsync(string sql)
        {
            var result = await _sessionPool.ExecuteQueryStatementAsync(sql,_options.Timeout);
            //await result.Close();
            //await CloseAsync();
            return result;
        }

        public void Dispose()
        {
            _sessionPool?.Close().ConfigureAwait(false).GetAwaiter().GetResult();
        }
    }
}
