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 CarTypeRepository : ICarTypeRepository
    {
        private readonly Repository<CarType> _repository;
        private readonly ICarRepository _carRepository;

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

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

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

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

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

        public async Task<bool> DeleteAsync(int typeId)
        {
            var cars = await _carRepository.GetListAsync(typeId);
            if (cars != null)
            {
                foreach (var car in cars)
                {
                    await _carRepository.DeleteAsync(car.Id);
                }
            }
            return await _repository.DeleteAsync(typeId);
        }
    }
}