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 MeetingLocationRepository : IMeetingLocationRepository
    {
        private readonly Repository<MeetingLocation> _repository;
        private readonly IMeetingRoomRepository _meetingRoomRepository;

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

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

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

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

        public async Task<IEnumerable<MeetingLocation>> GetListAsync()
        {
            return await _repository.GetAllAsync(Q.OrderByDesc(nameof(MeetingLocation.Taxis)));
        }

        public async Task<bool> DeleteAsync(int locationId)
        {
            var meetingRooms = await _meetingRoomRepository.GetListAsync(locationId);
            if (meetingRooms != null)
            {
                foreach (var meetingRoom in meetingRooms)
                {
                    await _meetingRoomRepository.DeleteAsync(meetingRoom.Id);
                }
            }
            return await _repository.DeleteAsync(locationId);
        }

        public async Task<string> GetAddress(int locationId)
        {
            return await _repository.GetAsync<string>(Q.Select(nameof(MeetingLocation.Address)).Where(nameof(MeetingLocation.Id), locationId));
        }
    }
}