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

namespace GxPress.Repository.Implement.WorkProcess
{
    public class ProcessRequestLimitRepository : IProcessRequestLimitRepository
    {
        private readonly Repository<ProcessRequestLimit> _repository;

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

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

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

        public async Task DeleteByProcessIdAsync(int processId)
        {
            await _repository.DeleteAsync(Q.Where(nameof(ProcessRequestLimit.ProcessId), processId));
        }

        public async Task<IEnumerable<ProcessRequestLimit>> GetListAsync(int processId)
        {
            return await _repository.GetAllAsync(Q
                .Where(nameof(ProcessRequestLimit.ProcessId), processId)
                .OrderByDesc(nameof(ProcessRequestLimit.Id))
            );
        }

        public async Task<IEnumerable<int>> GetProcessIdListByDepartmentIdAsync(int departmentId)
        {
            return await _repository.GetAllAsync<int>(Q
                .Select(nameof(ProcessRequestLimit.ProcessId))
                .Where(nameof(ProcessRequestLimit.DepartmentId), departmentId)
                .OrWhere(nameof(ProcessRequestLimit.DepartmentId), 0)
            );
        }
    }
}