using System.Collections.Generic;
using System.Threading.Tasks;
using GxPress.Common.AppOptions;
using GxPress.Common.Tools;
using GxPress.Entity.WorkFlow;
using GxPress.EnumConst;
using GxPress.Repository.Interface.WorkFlow;
using GxPress.Request.App.Flow;
using Microsoft.Extensions.Options;
using Datory;

namespace GxPress.Repository.Implement.WorkFlow
{
    public class FlowMessageRepository : IFlowMessageRepository
    {
        private readonly Repository<FlowMessage> _repository;

        public FlowMessageRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<FlowMessage>(database);
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

        public async Task<int> InsertAsync(FlowMessage item)
        {
            return await _repository.InsertAsync(item);
        }

        public async Task<IEnumerable<FlowMessage>> GetListByFlowIdAsync(int flowId, string type)
        {
            return await _repository.GetAllAsync(Q
                .Where(nameof(FlowMessage.FlowId), flowId)
                .Where(nameof(FlowMessage.Type), type)
                .OrderByDesc(nameof(FlowMessage.Id))
            );
        }

        public async Task<bool> DeleteAllAsync(int flowId)
        {
            return await _repository.DeleteAsync(Q
                .Where(nameof(FlowMessage.FlowId), flowId)
            ) > 0;
        }
    }
}