﻿using Discord.WebSocket;
using JhinBot.DiscordObjects;
using JhinBot.Utils;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace JhinBot.Services
{
    public class GreetService : IGreetService
    {
        private const string pattern = "%user%";
        private readonly DiscordSocketClient _client;
        private readonly IDbService _dbService;
        private readonly IOwnerLogger _ownerLogger;
        private readonly IEmbedService _embedService;
        private readonly IBotConfig _botConfig;

        public GreetService(DiscordSocketClient client, IDbService dbService, IOwnerLogger ownerLogger,
                            IEmbedService embedService, IBotConfig botConfig)
        {
            _client = client;
            _dbService = dbService;
            _ownerLogger = ownerLogger;
            _embedService = embedService;
            _botConfig = botConfig;
            _client.UserJoined += UserJoinedGuild;
        }

        private async Task UserJoinedGuild(SocketGuildUser arg)
        {
            using (var uow = _dbService.UnitOfWork)
            {
                var guildConfig = uow.GuildConfigRepo.For(arg.Guild.Id, set => set);
                if (guildConfig.SendGreetMessageOnJoin)
                {
                    var greetChannelId = guildConfig.GreetMessageChannelId;
                    if (greetChannelId == 0)
                        await _ownerLogger.LogMissingGuildConfigParameter("GreetChannelId", ToString(), arg.Guild.Name);
                    else
                    {
                        Regex rgx = new Regex(pattern);
                        string message = rgx.Replace(guildConfig.GreetMessage, arg.Mention);

                        var channel = arg.Guild.GetTextChannel(greetChannelId);
                        var embed = _embedService.CreateEmbed("Welcome!", _botConfig.EventColor, arg, message);
                        var toDelete = await channel.SendMessageAsync(arg.Mention, false, embed);

                        if (guildConfig.AutoDeleteGreet)
                            toDelete.DeleteAfter(30);
                    }
                }
            }
        }
    }
}