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

namespace GxPress.Repository.Implement.WorkCar
{
    public class CarRepository : ICarRepository
    {
        private readonly Repository<Car> _repository;

        public CarRepository(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<Car>(database, cache);
        }

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

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

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

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

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

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

        public async Task<int> GetAvailableCarId(int typeId, IEnumerable<int> orderedCarIds)
        {
            return await _repository.GetAsync<int>(Q
                .Select(nameof(Car.Id))
                .Where(nameof(Car.TypeId), typeId)
                .WhereNotIn(nameof(Car.Id), orderedCarIds)
            );
        }
    }
}