using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace Net.Project.B.Quest
{
    public interface IQuestService
    {
        public IReadOnlyDictionary<int,IQuestData> Quests { get; }
        public event Action<IQuestData,QuestState,QuestState> OnQuestCreatedOrUpdated;
        IQuestData AddOrUpdateQuest(IQuestData questData);
    }
    public class QuestService : IQuestService
    {
        //自动实现
        private readonly ILogger<QuestService> _logger;
        public IReadOnlyDictionary<int, IQuestData> Quests => _quests;
        public event Action<IQuestData, QuestState, QuestState> OnQuestCreatedOrUpdated;
        private readonly ConcurrentDictionary<int,IQuestData> _quests = new();

        public QuestService(ILogger<QuestService> logger)
        {
            _logger = logger;
        }

        public IQuestData AddOrUpdateQuest(IQuestData questData)
        {
            if (_quests.TryAdd(questData.Identity, questData))
            {
                OnQuestCreatedOrUpdated?.Invoke(questData,QuestState.Inactive,questData.CurrentState);
                _logger.LogInformation($"任务:{questData.Name}已创建");
            }
            else
            {
                var currentState = _quests[questData.Identity].CurrentState;
                _quests[questData.Identity] = questData;
                OnQuestCreatedOrUpdated?.Invoke(questData,currentState,questData.CurrentState);
                _logger.LogInformation($"任务:{questData.Name}已更新状态,从{currentState}更新为{questData.CurrentState}");
            }
            return questData;
        }
    }
}