using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Tools;
using GxPress.Entity.WorkMeeting;
using GxPress.Repository.Interface.WorkMeeting;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using SqlKata;

namespace GxPress.Repository.Implement.WorkMeeting
{
    public class MeetingOrderRepository : IMeetingOrderRepository
    {
        private readonly Repository<MeetingOrder> _repository;

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

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

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

        public async Task<IEnumerable<MeetingOrder>> GetListAsync(int roomId)
        {
            return await _repository.GetAllAsync(Q.Where(nameof(MeetingOrder.RoomId), roomId));
        }

        public async Task<IEnumerable<MeetingOrder>> GetListByMeetingIdAsync(int meetingId)
        {
            return await _repository.GetAllAsync(Q.Where(nameof(MeetingOrder.MeetingId), meetingId).OrderByDesc(nameof(MeetingOrder.Date)));
        }

        public async Task<IEnumerable<MeetingOrder>> GetListAsyncSinceNow(int roomId)
        {
            return await _repository.GetAllAsync(Q
                .Where(nameof(MeetingOrder.Date), ">=",
                StringUtils.GetDate(DateTime.Now)).Where(nameof(MeetingOrder.RoomId), roomId)
            );
        }


        public async Task<bool> DeleteAsync(int orderId)
        {
            return await _repository.DeleteAsync(orderId);
        }

        public async Task DeleteByRoomIdAsync(int roomId)
        {
            await _repository.DeleteAsync(Q.Where(nameof(MeetingOrder.RoomId), roomId));
        }

        public async Task DeleteByMeetingIdAsync(int meetingId)
        {
            await _repository.DeleteAsync(Q.Where(nameof(MeetingOrder.MeetingId), meetingId));
        }

        public async Task<bool> DeleteAsync(Query query)
        {
            return await _repository.DeleteAsync(query) > 0;
        }
    }
}