using Knoks.Core.Data.Interfaces;
using Knoks.Core.Entities;
using Knoks.Framework.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Knoks.Core.Data.Dao
{
    public class TagDao : ITagDao
    {
        public readonly int CustomId = -1;

        private readonly IProcExecutor _executor;
        public TagDao(IProcExecutor executor) {
            this._executor = executor;

        }
        public async Task<List<AnalysisTag>> GetTags(int tagType)
        {
            var result = await _executor.Go("BO_AnalysisTags", new { TypeId = tagType });
            return result.Тables[0].ToListMapped<AnalysisTag>().ToList();

        }
        public async Task<List<AnalysisTag>> GetKnokTags(int knokId, int tagType)
        {
            var result = await _executor.Go("BO_GetKnokTags", new { KnokId = knokId, AnalysisTypeId = tagType });
            return result.Тables[0].ToListMapped<AnalysisTag>().ToList();
        }

        public async Task<List<AnalysisTag>> SaveKnokTags(int knokId, IEnumerable<AnalysisTag> tags, int tagType)
        {
            var old = await GetKnokTags(knokId, tagType);
            var remove = old.Where(it => !tags.Any(t => t.AnalysisTagId == it.AnalysisTagId && (t.AnalysisTagId != CustomId || t.Name == it.Name))).ToList();
            var add = tags.Where(it=>!old.Any(t => t.AnalysisTagId == it.AnalysisTagId && (t.AnalysisTagId != CustomId || t.Name == it.Name))).ToList();
            await Task.WhenAll(remove.Select(it => _executor.Go("BO_RemoveKnokTag", new { KnokId = knokId, AnalysisTagId = it.AnalysisTagId, Name = it.Name, AnalysisTypeId = tagType })));
            await Task.WhenAll(add.Select(it => 
                _executor.Go("BO_AddKnokTag", new { KnokId = knokId, AnalysisTagId = it.AnalysisTagId, Name = it.Name, AnalysisTypeId = tagType }
            )));
            return await GetKnokTags(knokId, tagType);
        }
    }
}
