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;

namespace GxPress.Repository.Implement.WorkMeeting
{
    public class MeetingRoomRepository : IMeetingRoomRepository
    {
        private readonly Repository<MeetingRoom> _repository;
        private readonly IMeetingOrderRepository _meetingOrderRepository;
        private readonly IMeetingRepository _meetingRepository;
        private readonly IMeetingSummaryRepository _meetingSummaryRepository;

        public MeetingRoomRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IDistributedCache cache, IMeetingOrderRepository meetingOrderRepository, IMeetingRepository meetingRepository, IMeetingSummaryRepository meetingSummaryRepository)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<MeetingRoom>(database, cache);
            _meetingOrderRepository = meetingOrderRepository;
            _meetingRepository = meetingRepository;
            _meetingSummaryRepository = meetingSummaryRepository;
        }

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

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

        public async Task UpdateAsync(MeetingRoom item)
        {
            await _repository.UpdateAsync(item);
        }

        public async Task<MeetingRoom> GetAsync(int meetingId)
        {
            return await _repository.GetAsync(meetingId);
        }

        public async Task<IEnumerable<MeetingRoom>> GetListAsync(int locationId)
        {
            if (locationId > 0)
            {
                return await _repository.GetAllAsync(Q.Where(nameof(MeetingRoom.LocationId), locationId).OrderByDesc(nameof(MeetingRoom.Taxis)));
            }
            return await _repository.GetAllAsync(Q.OrderByDesc(nameof(MeetingRoom.Taxis)));
        }

        public async Task<bool> DeleteAsync(int roomId)
        {
            await _meetingOrderRepository.DeleteByRoomIdAsync(roomId);
            await _meetingRepository.DeleteByRoomIdAsync(roomId);
            await _meetingSummaryRepository.DeleteByRoomIdAsync(roomId);
            return await _repository.DeleteAsync(roomId);
        }
    }
}