public async Task <bool> SetNewNameViaMode <T>(IGuildUser cuser, FortniteUser usr, IUserMessage msg, IFortniteProfile classPveOrPvp, bool updateFromMyDb = false) where T : class
        {
            var ns = usr.NameStates.First(f => f.DiscordServerId == cuser.Guild.Id.ToString());

            if (usr.GameUserMode == GameUserMode.PVE)
            {
                if (!updateFromMyDb)
                {
                    var mapUser = await Api.GetPVEProfileById(usr.EpicId);

                    if (mapUser.Value != null)
                    {
                        return(await Context.Repo.UpdateDatabasePVEProfileAsync(mapUser, cuser, msg, usr.NameTag, ns.LockName, Context.GuildConfig.Owner.PVEDecimalState));
                    }
                }
                else
                {
                    Context.Repo.Db <FortniteUser>()
                    .Update(usr);
                    Context.Repo.Commit();
                    var pveTable = (FortnitePVEProfile)classPveOrPvp;
                    return(await Context.Repo.UpdateDiscordPVEProfileAsync(pveTable, usr.NameTag, cuser, msg, ns.LockName, Context.GuildConfig.Owner.PVEDecimalState));
                }
                await msg.SetErrorAsync();

                return(false);
            }
            else if (usr.GameUserMode == GameUserMode.PVP_WIN_ALL)
            {
                if (!updateFromMyDb)
                {
                    var mapUser = await Api.GetPVPProfileById(usr.EpicId);

                    if (mapUser.Value != null)
                    {
                        if (mapUser.Value.IsPrivate)
                        {
                            msg = await ReplyEmbedAsync(ToTranslate(BotTranslationString.PvpProfilIsNotPublic, GetLanguage(), cuser.Mention));
                        }
                        return(await Context.Repo.UpdateDatabasePVPProfileAsync(mapUser, cuser, msg, usr.NameTag, ns.LockName));
                    }
                }
                else
                {
                    Context.Repo.Db <FortniteUser>()
                    .Update(usr);
                    Context.Repo.Commit();
                    var pvpTable = (FortnitePVPProfile)classPveOrPvp;
                    return(await Context.Repo.UpdateDiscordPVPProfileAsync(pvpTable, usr.NameTag, cuser, msg, ns.LockName));
                }
                await msg.SetErrorAsync();

                return(false);
            }
            return(false);
        }
        public async Task <bool> UpdateDiscordPVPProfileAsync(FortnitePVPProfile mockUser, bool nameTag, IGuildUser guser, IUserMessage msg = null, bool IsNameLocked = false)
        {
            if (guser.IsServerOwner())
            {
                return(true);
            }

            var curUser = await guser.Guild.GetCurrentUserAsync(CacheMode.AllowDownload, Core.Utils.RequestOption);

            var mn_NickName = curUser.GuildPermissions.ManageNicknames;

            if (msg != null && IsNameLocked)
            {
                await msg.SetLockAsync();
            }

            if (mn_NickName)
            {
                try
                {
                    var newWinName = ModifyPVPTag(mockUser.PlayerName, mockUser.PvpCurrentModeWins(GameUserMode.PVP_WIN_ALL), nameTag);
                    var changeName = newWinName != guser?.Nickname;

                    if (!changeName)
                    {
                        return(true);
                    }
                    else if (IsNameLocked)
                    {
                        return(true);
                    }

                    guser.ModifyAsync((o) =>
                    {
                        if (curUser.GuildPermissions.ManageNicknames && IsNameLocked == false)
                        {
                            o.Nickname = newWinName;
                        }
                    }, Core.Utils.RequestOption).Wait();
                }
                catch (Exception e)
                {
                    if (msg != null)
                    {
                        await msg.SetErrorAsync();

                        return(false);
                    }
                }
            }
            return(true);
        }
        private Task PullMessage_OnAction(ReadyToVerify arg)
        {
            if (arg.JustDeQueue)
            {
                FriendListApi.DeclineFriendRequest(arg.EpicId).Wait();
                return(Task.CompletedTask);
            }
            var spanTime = DateTimeOffset.UtcNow - arg.Expire;

            if (spanTime.TotalSeconds >= 0 && FriendListApi.IsAuthorized)
            {
                try
                {
                    var          usr     = DiscordApi.GetApi.GetUserAsync(arg.DiscordUserId.ToUlong()).Result;
                    var          channel = (IMessageChannel)DiscordApi.GetApi.GetChannelAsync(arg.ChannelId).Result;
                    IUserMessage msg     = null;
                    try
                    {
                        msg = (IUserMessage)channel.GetMessageAsync(arg.MessageId, options: Core.Utils.RequestOption).Result;
                    }
                    catch (Exception e)
                    {
                        return(Task.CompletedTask);
                    }

                    if (usr != null)
                    {
                        FortniteUser dbAccount = Context.FortniteUsers.Find(arg.DiscordUserId);
                        if (dbAccount == null)
                        {
                            msg?.SetErrorAsync()?.Wait();
                            return(Task.CompletedTask);
                        }

                        var verificationResult = FriendListApi.DeclineFriendRequest(arg.EpicId).Result;
                        if (verificationResult)
                        {
                            if (dbAccount.IsValidName)
                            {
                                dbAccount.VerifiedProfile      = true;
                                dbAccount.LastUpDateTime       = DateTimeOffset.UtcNow;
                                Context.Entry(dbAccount).State = EntityState.Modified;
                                Context.SaveChanges();
                                msg?.SetSuccessAsync()?.Wait();
                            }
                            else
                            {
                                msg?.SetQuestionMarkAsync()?.Wait();
                            }
                        }
                        else
                        {
                            msg?.SetErrorAsync()?.Wait();
                        }
                    }
                    else
                    {
                        msg?.SetErrorAsync()?.Wait();
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    var verifyFinished = Context.VerifyOrders.Find(arg.EpicId);
                    if (verifyFinished != null)
                    {
                        Context.VerifyOrders.Remove(verifyFinished);
                        Context.SaveChanges();
                    }
                }
            }
            else
            {
                Redis
                .ListLeftPush(QueueName, arg, flags: CommandFlags.FireAndForget);
            }
            return(Task.CompletedTask);
        }
        public async Task <bool> UpdateDiscordPVEProfileAsync(FortnitePVEProfile mockUser, bool nameTag, IGuildUser guser, IUserMessage msg = null, bool IsNameLocked = false, bool PVEDecimals = true)
        {
            if (guser.IsServerOwner())
            {
                return(true);
            }

            var gconfig   = Guild.GetConfig(guser.Guild.Id.ToString());
            var UserRoles = await guser.GetUserRolesAsync(gconfig.Owner.DefaultLanguage);

            var addRole = true;
            var curUser = await guser.Guild.GetCurrentUserAsync(CacheMode.AllowDownload, Core.Utils.RequestOption);

            if (curUser.GuildPermissions.ManageRoles)
            {
                try
                {
                    foreach (var role in UserRoles)
                    {
                        if (role.Key == mockUser.Map)
                        {
                            addRole = false;
                            continue;
                        }
                        guser.RemoveRoleAsync(role.Value, Core.Utils.RequestOption).Wait();
                    }
                }
                catch (Exception e)
                {
                }

                if (!gconfig.Event.MythicSKStates.Active)//mythic storm king role remover
                {
                    try
                    {
                        ulong msk_roleId = ulong.Parse(gconfig.Event.MythicSKStates.RoleIdToMythicSK);
                        var   userRole   = guser.RoleIds.Any(id => id == msk_roleId);
                        if (userRole)
                        {
                            var role = guser.Guild.GetRole(msk_roleId);
                            guser.RemoveRoleAsync(role, Core.Utils.RequestOption).Wait();
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
                if (!gconfig.Event.EliteFrostnite2019s.Active)//elite frostnite 2019 role remover
                {
                    try
                    {
                        ulong msk_roleId = ulong.Parse(gconfig.Event.EliteFrostnite2019s.RoleId);
                        var   userRole   = guser.RoleIds.Any(id => id == msk_roleId);
                        if (userRole)
                        {
                            var role = guser.Guild.GetRole(msk_roleId);
                            guser.RemoveRoleAsync(role, Core.Utils.RequestOption).Wait();
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
            }

            var mn_NickName = curUser.GuildPermissions.ManageNicknames;
            var nm_Role     = curUser.GuildPermissions.ManageRoles;

            if (msg != null && IsNameLocked)
            {
                await msg.SetLockAsync();
            }

            if ((mn_NickName || nm_Role))
            {
                try
                {
                    //
                    if (mockUser.NumMythicSchematics > 0 && gconfig.Event.MythicSKStates.Active)
                    {
                        ulong msk_roleId = ulong.Parse(gconfig.Event.MythicSKStates.RoleIdToMythicSK);
                        var   userRole   = guser.RoleIds.Any(id => id == msk_roleId);
                        if (!userRole)
                        {
                            var guild_msk_role = guser.Guild.GetRole(msk_roleId);
                            guser.AddRoleAsync(guild_msk_role).Wait();
                        }
                    }
                    if (mockUser.EliteFortnite2019 && gconfig.Event.EliteFrostnite2019s.Active)
                    {
                        ulong msk_roleId = ulong.Parse(gconfig.Event.EliteFrostnite2019s.RoleId);
                        var   userRole   = guser.RoleIds.Any(id => id == msk_roleId);
                        if (!userRole)
                        {
                            var guild_efn_role = guser.Guild.GetRole(msk_roleId);
                            guser.AddRoleAsync(guild_efn_role).Wait();
                        }
                    }
                    //
                    var newPowerName = ModifyPVETag(mockUser.PlayerName, mockUser.AccountPowerLevel, nameTag, PVEDecimals);
                    var sameName     = newPowerName != guser?.Nickname;

                    if (!addRole && !sameName)
                    {
                        return(true);
                    }
                    else if (!addRole && IsNameLocked)
                    {
                        return(true);
                    }

                    guser.ModifyAsync((o) =>
                    {
                        if (curUser.GuildPermissions.ManageNicknames && IsNameLocked == false)
                        {
                            o.Nickname = newPowerName;
                        }

                        if (addRole && curUser.GuildPermissions.ManageRoles)
                        {
                            var CurrentGuildMapRoles = guser.Guild.GetMapRolesAsync(gconfig.Owner.DefaultLanguage).Result;
                            var rl = CurrentGuildMapRoles.FirstOrDefault(p => p.Key == mockUser.Map);
                            if (rl.Value != null)
                            {
                                guser.AddRoleAsync(rl.Value, Core.Utils.RequestOption).Wait();
                            }
                        }
                    }, Core.Utils.RequestOption).Wait();

                    if (msg != null && guser.Id == guser.Guild.OwnerId)
                    {
                        await msg.SetErrorAsync();
                    }
                }
                catch (Exception e)
                {
                    if (msg != null)
                    {
                        await msg.SetErrorAsync();

                        return(false);
                    }
                }
            }
            return(true);
        }
        /*
         * public async Task _HelpCmd()
         * {
         *  var cmds1 = "";
         *  var cmds2 = "";
         *  var cuser = this.Context.Guild.GetUser(this.Context.User.Id);
         *
         *  if (cuser.IsServerOwner() || cuser.Username == "Kesintisiz")
         *  {
         *      cmds1 += $"__**Server Owner**__\n" +
         *              $"**f.lang <TR/EN/RU/ES/DE/PT/FR/NL>** :changes the native bot response language\n" +
         *              $"**f.pve.maproles.add** :manually adds none/Stonewood/Plankerton/CannyValley/TwinePeaks map roles\n" +
         *              $"**f.restrict.role <ROLE NAME>** :specific access to **f.pve...** commands for usage\n" +
         *              $"**f.restrict.role.remove <ROLE NAME>** :removes specific role from access list\n" +
         *              $"**f.restrict.role.clear** :everyone in discord can use **f.pve....** commands\n\n";
         *  }
         *
         *  if (cuser.GuildPermissions.Administrator || cuser.IsServerOwner() || cuser.Username == "Kesintisiz")
         *  {
         *      cmds1 += $"  __**Administrator**__\n" +
         *              $"**f.state.decimals <ON/OFF>** :(default:on)controls the state of displaying decimal point of power level at current discord\n" +
         *              $"**f.state.autoremove <ON/OFF>** :(default:off)remove user request after FTN Power responds\n" +
         *              $"**f.stat** :how many user are there in discord server\n" +
         *              $"**f.helpme <MSG>** :sends private help message to FTN Power Developer\n" +
         *              $"**f.check.webhook** :checks webhook configurations for Mission Alert and Daily Llama\n" +
         *              $"**f.discord.info** :shows current discord's bot information\n\n";
         *  }
         *
         *  if (cuser.GuildPermissions.ManageNicknames || cuser.GuildPermissions.ManageRoles || cuser.Username == "Kesintisiz")
         *  {
         *      cmds1 += $"  __*needs ManageRoles + ManageNicknames Permisions to use(can be moderator)*__\n" +
         *              $"**f.user.mode @MENTION <PVE/PVP>** :changes mentioned user's game mode(like f.mode)\n" +
         *              $"**f.user.info @MENTION** :CHANGES mentioned user's information\n" +
         *              $"**f.user.name @MENTION <EPIC NAME>** :sets a name to mentioned user (like f.name)\n" +
         *              $"**f.user.update @MENTION** :adds user to queue for account power check (like f.update/f.up)\n\n";
         *  }
         *
         *  cmds2 += $"  __**PVE User**__\n" +
         *           $"**f.verify** :profile verification via FTN Power\n" +
         *           $"**f.mode <PVE/PVP>** :changes your game mode\n" +
         *           $"**f.pve** :current user's stats\n" +
         *           $"**f.pve <EPIC NAME>** :specified user stats\n" +
         *           $"**f.pve.survivors** :calculation of current squads resources\n" +
         *          $"**f.pr <EPIC NAME>** OR **f.pve.resources <EPIC NAME>** :specified user's resources\n" +
         *          $"**f.pr** OR **f.pve.resources** :list of current user's resources\n" +
         *          //  $"**f.pa** OR **f.pve.alerts** :list of current user's Alerts\n" +
         *          //    $"**f.pa <EPIC NAME>** OR **f.pve.alerts <EPIC NAME>** :specific user's Alerts\n" +
         *          $"**f.ps** OR **f.pve.missions** :pve mission alerts\n" +
         *          $"**f.pm** OR **f.pve.missions <vbuck/legendary/epic/legend survivor/legend perk/epic perk>** :filtered mission alerts\n" +
         *          $"**f.patch** :Fortnite Patch Notes\n" +
         *          $"**f.lock** :locks name changes in typed discord by FTN Power\n" +
         *          $"**f.unlock** :un-locks name changes in typed discord by FTN Power\n" +
         *          $"**f.link <EPIC NAME>** OR **f.name <EPIC NAME>** :sets/links a fortnite username(default:PVE)\n" +
         *          $"**f.unlink** :removes your Epic Name from bot\n" +
         *          $"**f.up** OR **f.update** :updates user's current GameMode status (according to discord nickname)\n" +
         *          $"**f.name.tag <LEFT/RIGHT>** :(default:LEFT)shows user power at the end of name or beginning of the name\n" +
         *          $"**f.donate** OR **f.info** :donation and help links\n" +
         *          $"**f.top** :shows current discord's Fortnite pve top list\n" +
         *          $"**f.top.global** :shows global Fortnite pve top list (which discord uses FTN Power)\n\n";
         *
         *  cmds2 += $"  __**PVP User**__\n" +
         *           $"**f.pvp.name <EPIC NAME>** :sets/links a fortnite username(PVP) (and adds to queue)\n" +
         *           $"**f.pvp.up** OR **f.up** :updates user's current GameMode status (according to discord nickname)\n" +
         *           $"**f.pvp** :current user's battle royale match stats\n" +
         *           $"**f.pvp <EPIC NAME>** :specified user's battle royale match stats\n\n";
         *
         *  if (cmds1 != "")
         *  {
         *      await this.ReplyEmbedAsync(cmds1, "FTN Power Commands");
         *  }
         *  if (cmds2 != "")
         *  {
         *      await this.ReplyEmbedAsync(cmds2, "FTN Power Commands");
         *  }
         *
         *  return;
         * }
         */
        public Task _NameChange(string mention, [Remainder] string newName)
        {
            return(Task.Run(async() =>
            {
                if (string.IsNullOrWhiteSpace(newName))
                {
                    return;
                }

                SocketGuildUser cuser = null;
                bool anotherUser = false;
                if (Context.Message.MentionedUsers.Count == 1 && !string.IsNullOrWhiteSpace(mention))
                {
                    anotherUser = true;
                    var u = Context.Message.MentionedUsers.First();

                    cuser = Context.Guild.GetUser(u.Id);
                }
                else
                {
                    cuser = Context.Guild.GetUser(Context.User.Id);
                }
                if (cuser.IsBot)
                {
                    return;
                }
                newName = newName.TrimStart('<').TrimEnd('>');
                if (!newName.ValidName())
                {
                    await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.ContainsNotAllowed, GetLanguage(), cuser.Mention));
                    Log.Write(Serilog.Events.LogEventLevel.Error, "user {UserName}({UserId}) in guild {GuildId} has no valid n-length, current is {UserNameLength} Text:'{WrongText}'", cuser.Username, cuser.Id, cuser.Guild.Id, newName.Length, newName);
                    return;
                }

                var uid = cuser.Id.ToString();
                var guid = cuser.Guild.Id.ToString();
                var usr = Context.DiscordUser;
                if (anotherUser)
                {
                    usr = Context.Repo.Db <FortniteUser>()
                          .GetById(uid);
                }
                if (usr == null)
                {
                    usr = await Context.Repo.User.AddOrGetUserAsync(uid, guid, GameUserMode.PVE);
                }
                NameState ns = usr.NameStates.FirstOrDefault(p => p.FortniteUserId == uid && p.DiscordServerId == guid);
                if (ns == null)
                {
                    ns = await Context.Repo.User.AddOrGetNameStateAsync(usr, guid);
                }
                else if (ns.LockName)
                {
                    await ReplyEmbedErrorAsync(ToTranslate(BotTranslationString.YourNameIsLocked, GetLanguage(), cuser.Mention));
                    return;
                }
                var pstate = await CheckUserPriority(new TimeSpan(0, 0, 10, 0), usr, cuser, ns);
                if (pstate.Value == null)
                {
                    return;
                }

                IUserMessage msg = null;
                var checkVerificationOfNewName = Api.GetUserIdByName(newName);
                if (checkVerificationOfNewName.Value == null)
                {
                    msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.NameWillBeUpdated, GetLanguage(), cuser.Mention, newName), pstate);
                    await msg?.SetErrorAsync();
                    return;
                }

                if (Context.Repo.Db <FortniteUser>().All().Any(f => f.VerifiedProfile && f.IsValidName && f.EpicId == checkVerificationOfNewName.Value.id && f.Id != uid))
                {
                    await ReplyEmbedErrorAsync($"you can not take {checkVerificationOfNewName.Value.displayName} Username, it is __already verified__ by account owner.");
                    return;
                }
                bool profileNotFoundButNameExists = false;
                if (Context.GuildConfig.Owner.DefaultGameMode == GameUserMode.PVE && Context.DiscordUser.GameUserMode == GameUserMode.NULL ||
                    Context.DiscordUser.GameUserMode == GameUserMode.PVE)
                {
                    Context.DiscordUser.VerifiedProfile = false;
                    Context.Repo.Db <FortniteUser>().Update(Context.DiscordUser);
                    Context.Repo.Commit();
                    msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.NameWillBeUpdated, GetLanguage(), cuser.Mention, newName), pstate);
                    var mapUser = await Api.GetPVEProfileByName(checkVerificationOfNewName.Value.displayName);
                    if (mapUser.Value != null)
                    {
                        await Context.Repo.UpdateDatabasePVEProfileAsync(mapUser, cuser, msg, Context.DiscordUser.NameTag, ns.LockName, Context.GuildConfig.Owner.PVEDecimalState);
                        return;
                    }
                    else
                    {
                        profileNotFoundButNameExists = checkVerificationOfNewName.Value != null;
                    }
                }
                else if (Context.GuildConfig.Owner.DefaultGameMode == GameUserMode.PVP_WIN_ALL && Context.DiscordUser.GameUserMode == GameUserMode.NULL ||
                         Context.DiscordUser.GameUserMode == GameUserMode.PVP_WIN_ALL)
                {
                    var mapUserPVP = await Api.GetPVPProfileByName(checkVerificationOfNewName.Value.displayName);
                    if (mapUserPVP.Value != null)
                    {
                        if (mapUserPVP.Value.IsPrivate)
                        {
                            msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.PvpProfilIsNotPublic, GetLanguage(), cuser.Mention), pstate);
                        }
                        else
                        {
                            Context.DiscordUser.VerifiedProfile = false;
                            Context.Repo.Db <FortniteUser>().Update(Context.DiscordUser);
                            Context.Repo.Commit();
                            msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.NameWillBeUpdated, GetLanguage(), cuser.Mention, newName), pstate);
                            await Context.Repo.UpdateDatabasePVPProfileAsync(mapUserPVP, cuser, msg, Context.DiscordUser.NameTag, ns.LockName);
                            return;
                        }
                    }
                    else
                    {
                        profileNotFoundButNameExists = checkVerificationOfNewName.Value != null;
                    }
                }
                if (profileNotFoundButNameExists)
                {
                    await msg?.SetConsolePlayerAsync();
                }
                else
                {
                    await msg?.SetErrorAsync();
                }
            }));
        }