Example #1
0
        private async void BtnCloneSelectedVersion_Click(object sender, RoutedEventArgs e)
        {
            var deck = DeckList.Instance.ActiveDeckVersion;

            if (deck == null)
            {
                return;
            }
            var cloneStats =
                (await
                 this.ShowMessageAsync("Clone game history?", "(Cloned games do not count towards class or overall stats.)",
                                       MessageDialogStyle.AffirmativeAndNegative,
                                       new MetroDialogSettings
            {
                AffirmativeButtonText = "clone history",
                NegativeButtonText = "do not clone history"
            })) == MessageDialogResult.Affirmative;
            var clone = (Deck)deck.CloneWithNewId(false);

            clone.ResetVersions();

            var originalStatsEntry = clone.DeckStats;

            /*while(DeckList.DecksList.Any(d => d.Name == clone.Name))
             * {
             *      var settings = new MetroDialogSettings {AffirmativeButtonText = "Set", DefaultText = clone.Name};
             *      var name =
             *              await
             *              this.ShowInputAsync("Name already exists", "You already have a deck with that name, please select a different one.", settings);
             *
             *      if(string.IsNullOrEmpty(name))
             *              return;
             *
             *      clone.Name = name;
             * }*/

            DeckList.Instance.Decks.Add(clone);
            DeckPickerList.UpdateDecks();
            DeckList.Save();
            ;

            var newStatsEntry = DeckStatsList.Instance.DeckStats.FirstOrDefault(ds => ds.BelongsToDeck(clone));

            if (newStatsEntry == null)
            {
                newStatsEntry = new DeckStats(clone);
                DeckStatsList.Instance.DeckStats.Add(newStatsEntry);
            }

            //clone game stats
            if (cloneStats)
            {
                foreach (var game in originalStatsEntry.Games)
                {
                    newStatsEntry.AddGameResult(game.CloneWithNewId());
                }
                Logger.WriteLine("cloned gamestats (version)", "Edit");
            }

            DeckStatsList.Save();
            //DeckPickerList.UpdateList();
            DeckPickerList.UpdateDecks();
            HearthStatsManager.UploadDeckAsync(clone);
        }
Example #2
0
#pragma warning disable 4014
        public async void HandleGameEnd()
        {
            Helper.MainWindow.Overlay.HideTimers();
            if (_game.CurrentGameStats == null || _handledGameEnd)
            {
                return;
            }
            if (_game.CurrentGameMode == GameMode.Spectator && !Config.Instance.RecordSpectator)
            {
                Logger.WriteLine("Game is in Spectator mode, discarded. (Record Spectator disabled)", "GameEventHandler");
                _assignedDeck = null;
                return;
            }
            var player   = _game.Entities.FirstOrDefault(e => e.Value.IsPlayer);
            var opponent = _game.Entities.FirstOrDefault(e => e.Value.HasTag(GAME_TAG.PLAYER_ID) && !e.Value.IsPlayer);

            if (player.Value != null)
            {
                _game.CurrentGameStats.PlayerName = player.Value.Name;
            }
            if (opponent.Value != null && CardIds.HeroIdDict.ContainsValue(_game.CurrentGameStats.OpponentHero))
            {
                _game.CurrentGameStats.OpponentName = opponent.Value.Name;
            }
            else
            {
                _game.CurrentGameStats.OpponentName = _game.CurrentGameStats.OpponentHero;
            }

            _game.CurrentGameStats.Turns = HsLogReaderV2.Instance.GetTurnNumber();
            if (Config.Instance.DiscardZeroTurnGame && _game.CurrentGameStats.Turns < 1)
            {
                Logger.WriteLine("Game has 0 turns, discarded. (DiscardZeroTurnGame)", "GameEventHandler");
                _assignedDeck = null;
                GameEvents.OnGameEnd.Execute();
                return;
            }
            _game.CurrentGameStats.GameEnd();
            GameEvents.OnGameEnd.Execute();
            var selectedDeck = DeckList.Instance.ActiveDeck;

            if (selectedDeck != null)
            {
                if (Config.Instance.DiscardGameIfIncorrectDeck &&
                    !_game.PlayerDrawn.All(
                        c =>
                        c.IsStolen ||
                        selectedDeck.GetSelectedDeckVersion().Cards.Any(c2 => c.Id == c2.Id && c.Count <= c2.Count)))
                {
                    if (Config.Instance.AskBeforeDiscardingGame)
                    {
                        var discardDialog = new DiscardGameDialog(_game.CurrentGameStats);
                        discardDialog.Topmost = true;
                        discardDialog.ShowDialog();
                        if (discardDialog.Result == DiscardGameDialogResult.Discard)
                        {
                            Logger.WriteLine("Assigned current game to NO deck - selected deck does not match cards played (dialogresult: discard)",
                                             "GameEventHandler");
                            _game.CurrentGameStats.DeleteGameFile();
                            _assignedDeck = null;
                            return;
                        }
                        if (discardDialog.Result == DiscardGameDialogResult.MoveToOther)
                        {
                            var moveDialog = new MoveGameDialog(DeckList.Instance.Decks.Where(d => d.Class == _game.CurrentGameStats.PlayerHero));
                            moveDialog.Topmost = true;
                            moveDialog.ShowDialog();
                            var targetDeck = moveDialog.SelectedDeck;
                            if (targetDeck != null)
                            {
                                selectedDeck = targetDeck;
                                _game.CurrentGameStats.PlayerDeckVersion        = moveDialog.SelectedVersion;
                                _game.CurrentGameStats.HearthStatsDeckVersionId = targetDeck.GetVersion(moveDialog.SelectedVersion).HearthStatsDeckVersionId;
                                //...continue as normal
                            }
                            else
                            {
                                Logger.WriteLine("No deck selected in move game dialog after discard dialog, discarding game", "GameEventHandler");
                                _game.CurrentGameStats.DeleteGameFile();
                                _assignedDeck = null;
                                return;
                            }
                        }
                    }
                    else
                    {
                        Logger.WriteLine("Assigned current game to NO deck - selected deck does not match cards played (no dialog)", "GameEventHandler");
                        _game.CurrentGameStats.DeleteGameFile();
                        _assignedDeck = null;
                        return;
                    }
                }
                else
                {
                    _game.CurrentGameStats.PlayerDeckVersion        = DeckList.Instance.ActiveDeckVersion.Version;
                    _game.CurrentGameStats.HearthStatsDeckVersionId = DeckList.Instance.ActiveDeckVersion.HearthStatsDeckVersionId;
                }

                _lastGame = _game.CurrentGameStats;
                selectedDeck.DeckStats.AddGameResult(_lastGame);
                selectedDeck.StatsUpdated();
                if (Config.Instance.ShowNoteDialogAfterGame && !Config.Instance.NoteDialogDelayed && !_showedNoteDialog)
                {
                    _showedNoteDialog = true;
                    new NoteDialog(_game.CurrentGameStats);
                }
                Logger.WriteLine("Assigned current game to deck: " + selectedDeck.Name, "GameStats");
                _assignedDeck = selectedDeck;

                // Unarchive the active deck after we have played a game with it
                if (_assignedDeck.Archived)
                {
                    Logger.WriteLine("Automatically unarchiving deck " + selectedDeck.Name + " after assigning current game", "GameEventHandler");
                    Helper.MainWindow.ArchiveDeck(_assignedDeck, false);
                }

                if (HearthStatsAPI.IsLoggedIn && Config.Instance.HearthStatsAutoUploadNewGames)
                {
                    if (_game.CurrentGameMode == GameMode.None)
                    {
                        await GameModeDetection(300); //give the user 5 minutes to get out of the victory/defeat screen
                    }
                    if (_game.CurrentGameMode == GameMode.Casual)
                    {
                        await HsLogReaderV2.Instance.RankedDetection();
                    }
                    if (_game.CurrentGameMode == GameMode.Ranked && !_lastGame.HasRank)
                    {
                        await RankDetection(5);
                    }
                    await GameModeSaved(15);

                    if (_game.CurrentGameMode == GameMode.Arena)
                    {
                        HearthStatsManager.UploadArenaMatchAsync(_lastGame, selectedDeck, background: true);
                    }
                    if (_game.CurrentGameMode == GameMode.Brawl)
                    { /* do nothing */
                    }
                    else
                    {
                        HearthStatsManager.UploadMatchAsync(_lastGame, selectedDeck, background: true);
                    }
                }
                _lastGame = null;
            }
            else
            {
                DefaultDeckStats.Instance.GetDeckStats(_game.PlayingAs).AddGameResult(_game.CurrentGameStats);
                Logger.WriteLine(string.Format("Assigned current deck to default {0} deck.", _game.PlayingAs), "GameStats");
                _assignedDeck = null;
            }
        }
 private void MenuItemHearthStatsSync_OnClick(object sender, RoutedEventArgs e) => HearthStatsManager.SyncAsync();
        public async void SaveDeck(bool overwrite, SerializableVersion newVersion, bool workInProgressDeck = false)
        {
            var deckName = TextBoxDeckName.Text;

            if (string.IsNullOrEmpty(deckName))
            {
                var settings = new MessageDialogs.Settings {
                    AffirmativeButtonText = "Set", DefaultText = deckName
                };

                var name = await this.ShowInputAsync("No name set", "Please set a name for the deck", settings);

                if (string.IsNullOrEmpty(name))
                {
                    return;
                }

                deckName             = name;
                TextBoxDeckName.Text = name;
            }

            if (_newDeck.Cards.Sum(c => c.Count) != 30 && workInProgressDeck == false)
            {
                var settings = new MessageDialogs.Settings {
                    AffirmativeButtonText = "Yes", NegativeButtonText = "No"
                };

                var result =
                    await
                    this.ShowMessageAsync("Not 30 cards",
                                          string.Format("Deck contains {0} cards. Is this what you want to save anyway?",
                                                        _newDeck.Cards.Sum(c => c.Count)), MessageDialogStyle.AffirmativeAndNegative, settings);

                if (result != MessageDialogResult.Affirmative)
                {
                    return;
                }
            }

            var previousVersion = _newDeck.Version;

            if (overwrite && (_newDeck.Version != newVersion))
            {
                AddDeckHistory();
                _newDeck.Version                  = newVersion;
                _newDeck.SelectedVersion          = newVersion;
                _newDeck.HearthStatsDeckVersionId = "";
            }

            if (EditingDeck && overwrite)
            {
                DeckList.Instance.Decks.Remove(_newDeck);
            }

            var oldDeckName = _newDeck.Name;

            _newDeck.Name = deckName;

            var newDeckClone = (Deck)_newDeck.Clone();

            newDeckClone.Archived = false;

            DeckList.Instance.Decks.Add(newDeckClone);

            newDeckClone.LastEdited = DateTime.Now;

            DeckList.Save();

            Logger.WriteLine("Saved Decks", "SaveDeck");

            if (EditingDeck)
            {
                TagControlEdit.SetSelectedTags(new List <string>());
                if (deckName != oldDeckName)
                {
                    var statsEntry = DeckStatsList.Instance.DeckStats.FirstOrDefault(ds => ds.BelongsToDeck(_newDeck));
                    if (statsEntry != null)
                    {
                        if (overwrite)
                        {
                            statsEntry.Name = deckName;
                            Logger.WriteLine("Deck has new name, updated deckstats", "SaveDeck");
                            foreach (var game in statsEntry.Games)
                            {
                                game.DeckName = deckName;
                            }
                        }
                        else
                        {
                            var newStatsEntry = DeckStatsList.Instance.DeckStats.FirstOrDefault(ds => ds.BelongsToDeck(_newDeck));
                            if (newStatsEntry == null)
                            {
                                newStatsEntry = new DeckStats(_newDeck);
                                DeckStatsList.Instance.DeckStats.Add(newStatsEntry);
                            }
                            foreach (var game in statsEntry.Games)
                            {
                                newStatsEntry.AddGameResult(game.CloneWithNewId());
                            }
                            Logger.WriteLine("cloned gamestats for \"Set as new\"", "SaveDeck");
                        }
                        DeckStatsList.Save();
                    }
                }
            }


            if (Config.Instance.HearthStatsAutoUploadNewDecks && HearthStatsAPI.IsLoggedIn)
            {
                Logger.WriteLine("auto uploading new/edited deck", "SaveDeck");
                if (EditingDeck)
                {
                    if (previousVersion != newVersion)
                    {
                        HearthStatsManager.UploadVersionAsync(newDeckClone, _originalDeck.HearthStatsIdForUploading, background: true);
                    }
                    else
                    {
                        HearthStatsManager.UpdateDeckAsync(newDeckClone, background: true);
                    }
                }
                else
                {
                    HearthStatsManager.UploadDeckAsync(newDeckClone, background: true);
                }
            }

            //after cloning the stats, otherwise new stats will be generated
            //DeckPickerList.AddAndSelectDeck(newDeckClone);
            if (EditingDeck)
            {
                DeckManagerEvents.OnDeckUpdated.Execute(newDeckClone);
            }
            else
            {
                DeckManagerEvents.OnDeckCreated.Execute(newDeckClone);
            }


            EditingDeck = false;

            foreach (var tag in _newDeck.Tags)
            {
                SortFilterDecksFlyout.AddSelectedTag(tag);
            }

            DeckPickerList.SelectDeckAndAppropriateView(newDeckClone);
            DeckPickerList.UpdateDecks(forceUpdate: new[] { newDeckClone });
            SelectDeck(newDeckClone, true);
            CloseNewDeck();
            ClearNewDeckSection();
        }
Example #5
0
        private void MoveGameToOtherDeck(List <GameStats> selectedGames)
        {
            if (selectedGames == null)
            {
                return;
            }

            var heroes = new Dictionary <string, int>();

            foreach (var game in selectedGames)
            {
                if (!heroes.ContainsKey(game.PlayerHero))
                {
                    heroes.Add(game.PlayerHero, 0);
                }
                heroes[game.PlayerHero]++;
            }

            var heroPlayed      = heroes.Any() ? heroes.OrderByDescending(x => x.Value).First().Key : "Any";
            var possibleTargets = DeckList.Instance.Decks.Where(d => d.Class == heroPlayed || heroPlayed == "Any");

            var dialog = new MoveGameDialog(possibleTargets);

            if (Config.Instance.StatsInWindow)
            {
                dialog.Owner = Helper.MainWindow.StatsWindow;
            }
            else
            {
                dialog.Owner = Helper.MainWindow;
            }

            dialog.ShowDialog();
            var selectedDeck = dialog.SelectedDeck;

            if (selectedDeck == null)
            {
                return;
            }
            foreach (var game in selectedGames)
            {
                var defaultDeck = DefaultDeckStats.Instance.DeckStats.FirstOrDefault(ds => ds.Games.Contains(game));
                if (defaultDeck != null)
                {
                    defaultDeck.Games.Remove(game);
                    DefaultDeckStats.Save();
                }
                else
                {
                    var deck = DeckList.Instance.Decks.FirstOrDefault(d => game.DeckId == d.DeckId);
                    if (deck != null)
                    {
                        deck.DeckStats.Games.Remove(game);
                    }
                }
                game.PlayerDeckVersion        = dialog.SelectedVersion;
                game.HearthStatsDeckVersionId = selectedDeck.GetVersion(dialog.SelectedVersion).HearthStatsDeckVersionId;
                game.DeckId   = selectedDeck.DeckId;
                game.DeckName = selectedDeck.Name;
                selectedDeck.DeckStats.Games.Add(game);
                if (HearthStatsAPI.IsLoggedIn && Config.Instance.HearthStatsAutoUploadNewGames)
                {
                    HearthStatsManager.MoveMatchAsync(game, selectedDeck, background: true);
                }
            }
            DeckStatsList.Save();
            DeckList.Save();
            Refresh();
            Helper.MainWindow.DeckPickerList.UpdateDecks();
        }
Example #6
0
        private async void DeleteGames(DataGrid dataGrid, bool overall)
        {
            MetroWindow window;

            if (Config.Instance.StatsInWindow)
            {
                window = Helper.MainWindow.StatsWindow;
            }
            else
            {
                window = Helper.MainWindow;
            }

            var count = dataGrid.SelectedItems.Count;

            if (count == 1)
            {
                var selectedGame = dataGrid.SelectedItem as GameStats;
                if (selectedGame == null)
                {
                    return;
                }

                if (await window.ShowDeleteGameStatsMessage(selectedGame) != MessageDialogResult.Affirmative)
                {
                    return;
                }
                if (!overall)
                {
                    if (_deck.DeckStats.Games.Contains(selectedGame))
                    {
                        selectedGame.DeleteGameFile();
                        _deck.DeckStats.Games.Remove(selectedGame);
                        Logger.WriteLine("Deleted game " + selectedGame + "(overall=" + overall + ")", "DeckStatsControl");
                        DeckStatsList.Save();
                    }
                }
                else
                {
                    var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckStats.Games.Contains(selectedGame));
                    if (deck != null)
                    {
                        if (deck.DeckStats.Games.Contains(selectedGame))
                        {
                            selectedGame.DeleteGameFile();
                            deck.DeckStats.Games.Remove(selectedGame);
                            Logger.WriteLine("Deleted game " + selectedGame + "(overall=" + overall + ")", "DeckStatsControl");
                            DefaultDeckStats.Save();
                        }
                    }
                    else
                    {
                        var deckstats = DefaultDeckStats.Instance.DeckStats.FirstOrDefault(ds => ds.Games.Contains(selectedGame));
                        if (deckstats != null)
                        {
                            selectedGame.DeleteGameFile();
                            deckstats.Games.Remove(selectedGame);
                            Logger.WriteLine("Deleted game " + selectedGame + "(overall=" + overall + ")", "DeckStatsControl");
                            DefaultDeckStats.Save();
                        }
                    }
                }
                if (HearthStatsAPI.IsLoggedIn && selectedGame.HasHearthStatsId && await Helper.MainWindow.CheckHearthStatsMatchDeletion())
                {
                    HearthStatsManager.DeleteMatchesAsync(new List <GameStats> {
                        selectedGame
                    });
                }
                //Helper.MainWindow.DeckPickerList.Items.Refresh();
                Helper.MainWindow.DeckPickerList.UpdateDecks();
                Refresh();
            }
            else if (count > 1)
            {
                if (await window.ShowDeleteMultipleGameStatsMessage(count) != MessageDialogResult.Affirmative)
                {
                    return;
                }
                var selectedGames = dataGrid.SelectedItems.Cast <GameStats>().Where(g => g != null).ToList();
                foreach (var selectedGame in selectedGames)
                {
                    if (!overall)
                    {
                        if (_deck.DeckStats.Games.Contains(selectedGame))
                        {
                            selectedGame.DeleteGameFile();
                            _deck.DeckStats.Games.Remove(selectedGame);
                            Logger.WriteLine("Deleted game " + selectedGame + "(overall=" + overall + ")", "DeckStatsControl");
                        }
                    }
                    else
                    {
                        var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckStats.Games.Contains(selectedGame));
                        if (deck != null)
                        {
                            if (deck.DeckStats.Games.Contains(selectedGame))
                            {
                                selectedGame.DeleteGameFile();
                                deck.DeckStats.Games.Remove(selectedGame);
                                Logger.WriteLine("Deleted game " + selectedGame + "(overall=" + overall + ")", "DeckStatsControl");
                            }
                        }
                        else
                        {
                            var deckstats = DefaultDeckStats.Instance.DeckStats.FirstOrDefault(ds => ds.Games.Contains(selectedGame));
                            if (deckstats != null)
                            {
                                selectedGame.DeleteGameFile();
                                deckstats.Games.Remove(selectedGame);
                                Logger.WriteLine("Deleted game " + selectedGame + "(overall=" + overall + ")", "DeckStatsControl");
                            }
                        }
                    }
                }

                if (HearthStatsAPI.IsLoggedIn && selectedGames.Any(g => g.HasHearthStatsId) &&
                    await Helper.MainWindow.CheckHearthStatsMatchDeletion())
                {
                    HearthStatsManager.DeleteMatchesAsync(selectedGames);
                }
                DeckStatsList.Save();
                DefaultDeckStats.Save();
                Logger.WriteLine("Deleted " + count + " games", "DeckStatsControl");
                Helper.MainWindow.DeckPickerList.UpdateDecks();
                Refresh();
            }
        }
        private async void DeleteDeck(Deck deck, bool saveAndUpdate = true)
        {
            if (deck == null)
            {
                return;
            }

            var deckStats = DeckStatsList.Instance.DeckStats.FirstOrDefault(ds => ds.BelongsToDeck(deck));

            if (deckStats != null)
            {
                if (deckStats.Games.Any())
                {
                    if (Config.Instance.KeepStatsWhenDeletingDeck)
                    {
                        var defaultDeck = DefaultDeckStats.Instance.GetDeckStats(deck.Class);
                        if (defaultDeck != null)
                        {
                            defaultDeck.Games.AddRange(deckStats.Games);
                        }
                        DefaultDeckStats.Save();
                        Logger.WriteLine(string.Format("Moved deckstats for deck {0} to default stats", deck.Name), "Edit");
                    }
                    else
                    {
                        try
                        {
                            foreach (var game in deckStats.Games)
                            {
                                game.DeleteGameFile();
                            }
                            Logger.WriteLine("Deleted games from deck: " + deck.Name, "Edit");
                        }
                        catch (Exception)
                        {
                            Logger.WriteLine("Error deleting games", "Edit");
                        }
                    }
                }
                DeckStatsList.Instance.DeckStats.Remove(deckStats);
                if (saveAndUpdate)
                {
                    DeckStatsList.Save();
                }
                Logger.WriteLine("Removed deckstats from deck: " + deck.Name, "Edit");
            }

            if (HearthStatsAPI.IsLoggedIn && deck.HasHearthStatsId && await CheckHearthStatsDeckDeletion())
            {
                HearthStatsManager.DeleteDeckAsync(deck, false, true);
            }

            DeckList.Instance.Decks.Remove(deck);
            if (saveAndUpdate)
            {
                DeckList.Save();
                DeckPickerList.UpdateDecks();
                DeckPickerList.UpdateArchivedClassVisibility();
            }
            ListViewDeck.ItemsSource = null;
            Logger.WriteLine("Deleted deck: " + deck.Name, "Edit");
        }
Example #8
0
        private async void DeleteGames(DataGrid dataGrid, bool overall)
        {
            var window = Config.Instance.StatsInWindow ? (MetroWindow)Core.Windows.StatsWindow : Core.MainWindow;

            var count = dataGrid.SelectedItems.Count;

            if (count == 1)
            {
                var selectedGame = dataGrid.SelectedItem as GameStats;
                if (selectedGame == null)
                {
                    return;
                }

                if (await window.ShowDeleteGameStatsMessage(selectedGame) != MessageDialogResult.Affirmative)
                {
                    return;
                }
                if (!overall)
                {
                    if (_deck.DeckStats.Games.Contains(selectedGame))
                    {
                        selectedGame.DeleteGameFile();
                        _deck.DeckStats.Games.Remove(selectedGame);
                        Log.Info($"Deleted game {selectedGame} (overall=false)");
                        DeckStatsList.Save();
                    }
                }
                else
                {
                    var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckStats.Games.Contains(selectedGame));
                    if (deck != null)
                    {
                        if (deck.DeckStats.Games.Contains(selectedGame))
                        {
                            selectedGame.DeleteGameFile();
                            deck.DeckStats.Games.Remove(selectedGame);
                            Log.Info($"Deleted game {selectedGame} (overall=true)");
                            DefaultDeckStats.Save();
                        }
                    }
                    else
                    {
                        var deckstats = DefaultDeckStats.Instance.DeckStats.FirstOrDefault(ds => ds.Games.Contains(selectedGame));
                        if (deckstats != null)
                        {
                            selectedGame.DeleteGameFile();
                            deckstats.Games.Remove(selectedGame);
                            Log.Info($"Deleted game {selectedGame} (overall=true)");
                            DefaultDeckStats.Save();
                        }
                    }
                }
                if (HearthStatsAPI.IsLoggedIn && selectedGame.HasHearthStatsId && await Core.MainWindow.ShowCheckHearthStatsMatchDeletionDialog())
                {
                    HearthStatsManager.DeleteMatchesAsync(new List <GameStats> {
                        selectedGame
                    }).Forget();
                }
                //Core.MainWindow.DeckPickerList.Items.Refresh();
                Core.MainWindow.DeckPickerList.UpdateDecks();
                Refresh();
            }
            else if (count > 1)
            {
                if (await window.ShowDeleteMultipleGameStatsMessage(count) != MessageDialogResult.Affirmative)
                {
                    return;
                }
                var selectedGames = dataGrid.SelectedItems.Cast <GameStats>().Where(g => g != null).ToList();
                foreach (var selectedGame in selectedGames)
                {
                    if (!overall)
                    {
                        if (_deck.DeckStats.Games.Contains(selectedGame))
                        {
                            selectedGame.DeleteGameFile();
                            _deck.DeckStats.Games.Remove(selectedGame);
                            Log.Info($"Deleted game {selectedGame} (overall=false)");
                        }
                    }
                    else
                    {
                        var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckStats.Games.Contains(selectedGame));
                        if (deck != null)
                        {
                            if (deck.DeckStats.Games.Contains(selectedGame))
                            {
                                selectedGame.DeleteGameFile();
                                deck.DeckStats.Games.Remove(selectedGame);
                                Log.Info($"Deleted game {selectedGame} (overall=true)");
                            }
                        }
                        else
                        {
                            var deckstats = DefaultDeckStats.Instance.DeckStats.FirstOrDefault(ds => ds.Games.Contains(selectedGame));
                            if (deckstats != null)
                            {
                                selectedGame.DeleteGameFile();
                                deckstats.Games.Remove(selectedGame);
                                Log.Info($"Deleted game {selectedGame} (overall=true)");
                            }
                        }
                    }
                }

                if (HearthStatsAPI.IsLoggedIn && selectedGames.Any(g => g.HasHearthStatsId) &&
                    await Core.MainWindow.ShowCheckHearthStatsMatchDeletionDialog())
                {
                    HearthStatsManager.DeleteMatchesAsync(selectedGames).Forget();
                }
                DeckStatsList.Save();
                DefaultDeckStats.Save();
                Log.Info("Deleted " + count + " games");
                Core.MainWindow.DeckPickerList.UpdateDecks();
                Refresh();
            }
        }
Example #9
0
        public static void Initialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var newUser = !Directory.Exists(Config.AppDataPath);

            Config.Load();
            Log.Initialize();
            ConfigManager.Run();
            LogConfigUpdater.Run().Forget();
            LogConfigWatcher.Start();
            Helper.UpdateAppTheme();
            ThemeManager.Run();
            var splashScreenWindow = new SplashScreenWindow();

            splashScreenWindow.ShowConditional();
            Game = new GameV2();
            LoginType loginType;
            var       loggedIn = HearthStatsAPI.LoadCredentials();

            if (!loggedIn && Config.Instance.ShowLoginDialog)
            {
                var loginWindow = new LoginWindow();
                splashScreenWindow.Close();
                loginWindow.ShowDialog();
                if (loginWindow.LoginResult == LoginType.None)
                {
                    Application.Current.Shutdown();
                    return;
                }
                loginType          = loginWindow.LoginResult;
                splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.ShowConditional();
            }
            else
            {
                loginType = loggedIn ? LoginType.AutoLogin : LoginType.AutoGuest;
            }
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            if (Config.Instance.ReselectLastDeckUsed)
            {
                MainWindow.SelectLastUsedDeck();
                Config.Instance.ReselectLastDeckUsed = false;
                Config.Save();
            }
            MainWindow.Show();
            splashScreenWindow.Close();

            if (ConfigManager.UpdatedVersion != null)
            {
                Updater.Cleanup();
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion);
                MainWindow.UpdateNotesControl.LoadUpdateNotes();
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

            Helper.CopyReplayFiles();
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn)
            {
                HearthStatsManager.SyncAsync(background: true);
            }

            PluginManager.Instance.LoadPlugins();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();

            if (Helper.HearthstoneDirExists)
            {
                if (LogConfigUpdater.LogConfigUpdateFailed)
                {
                    MainWindow.ShowLogConfigUpdateFailedMessage().Forget();
                }
                else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning)
                {
                    MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted.");
                    Overlay.ShowRestartRequiredWarning();
                }
                LogReaderManager.Start(Game);
            }
            else
            {
                MainWindow.ShowHsNotInstalledMessage().Forget();
            }

            NewsUpdater.UpdateAsync();
            HotKeyManager.Load();

            if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning)
            {
                Helper.StartHearthstoneAsync();
            }

            Initialized = true;

            Analytics.Analytics.TrackPageView($"/app/v{Helper.GetCurrentVersion().ToVersionString()}/{loginType.ToString().ToLower()}{(newUser ? "/new" : "")}", "");
        }
        private void MoveGameToOtherDeck(GameStats selectedGame)
        {
            if (selectedGame == null)
            {
                return;
            }

            var heroes = new Dictionary <string, int>();

            foreach (var turn in selectedGame.TurnStats)
            {
                foreach (var play in turn.Plays)
                {
                    if (!play.Type.ToString().Contains("Player"))
                    {
                        continue;
                    }
                    var hero = Game.GetCardFromId(play.CardId).PlayerClass;
                    if (hero == null)
                    {
                        continue;
                    }
                    if (!heroes.ContainsKey(hero))
                    {
                        heroes.Add(hero, 0);
                    }
                    heroes[hero]++;
                }
            }


            var heroPlayed = heroes.Any() ? heroes.OrderByDescending(x => x.Value).First().Key : "Any";

            var possibleTargets = DeckList.Instance.Decks.Where(d => d.Class == heroPlayed || heroPlayed == "Any");

            var dialog = new MoveGameDialog(possibleTargets);

            if (Config.Instance.StatsInWindow)
            {
                dialog.Owner = Helper.MainWindow.StatsWindow;
            }
            else
            {
                dialog.Owner = Helper.MainWindow;
            }

            dialog.ShowDialog();
            var selectedDeck = dialog.SelectedDeck;

            if (selectedDeck == null)
            {
                return;
            }
            var defaultDeck = DefaultDeckStats.Instance.DeckStats.FirstOrDefault(ds => ds.Games.Contains(selectedGame));

            if (defaultDeck != null)
            {
                defaultDeck.Games.Remove(selectedGame);
                DefaultDeckStats.Save();
            }
            else
            {
                _deck.DeckStats.Games.Remove(selectedGame);
            }
            selectedGame.PlayerDeckVersion        = selectedDeck.Version;      //move to latest version
            selectedGame.HearthStatsDeckVersionId = selectedDeck.HearthStatsDeckVersionId;
            selectedDeck.DeckStats.Games.Add(selectedGame);
            DeckStatsList.Save();
            DeckList.Save();
            ;
            Refresh();
            Helper.MainWindow.DeckPickerList.UpdateDecks();
            if (HearthStatsAPI.IsLoggedIn && Config.Instance.HearthStatsAutoUploadNewGames)
            {
                HearthStatsManager.MoveMatchAsync(selectedGame, selectedDeck, background: true);
            }
        }
Example #11
0
        public static void Initialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var newUser = !Directory.Exists(Config.AppDataPath);

            Config.Load();
            ConfigManager.Run();
            Logger.Initialzie();
            Helper.UpdateAppTheme();
            var splashScreenWindow = new SplashScreenWindow();

            splashScreenWindow.ShowConditional();
            Game = new GameV2();
            LoginType loginType;
            var       loggedIn = HearthStatsAPI.LoadCredentials();

            if (!loggedIn && Config.Instance.ShowLoginDialog)
            {
                var loginWindow = new LoginWindow();
                splashScreenWindow.Close();
                loginWindow.ShowDialog();
                if (loginWindow.LoginResult == LoginType.None)
                {
                    Application.Current.Shutdown();
                    return;
                }
                loginType          = loginWindow.LoginResult;
                splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.ShowConditional();
            }
            else
            {
                loginType = loggedIn ? LoginType.AutoLogin : LoginType.AutoGuest;
            }
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            MainWindow.Show();
            splashScreenWindow.Close();

            if (ConfigManager.UpdatedVersion != null)
            {
                Updater.Cleanup();
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.LoadUpdateNotes();
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

            if (Helper.HearthstoneDirExists)
            {
                if (Helper.UpdateLogConfig && Game.IsRunning)
                {
                    MainWindow.ShowMessageAsync("Restart Hearthstone",
                                                "This is either your first time starting HDT or the log.config file has been updated. Please restart Hearthstone, for HDT to work properly.");
                }
                LogReaderManager.Start(Game);
            }
            else
            {
                MainWindow.ShowHsNotInstalledMessage();
            }

            Helper.CopyReplayFiles();
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn)
            {
                HearthStatsManager.SyncAsync(background: true);
            }

            PluginManager.Instance.LoadPlugins();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();
            NewsUpdater.UpdateAsync();
            HotKeyManager.Load();
            Initialized = true;

            Analytics.Analytics.TrackPageView(
                string.Format("/app/v{0}/{1}{2}", Helper.GetCurrentVersion().ToVersionString(),
                              loginType.ToString().ToLower(), newUser ? "/new" : ""), "");
        }
Example #12
0
#pragma warning disable 4014
        public static async void HandleGameEnd()
        {
            Helper.MainWindow.Overlay.HideTimers();
            if (Game.CurrentGameStats == null)
            {
                return;
            }
            var player   = Game.Entities.FirstOrDefault(e => e.Value.IsPlayer);
            var opponent = Game.Entities.FirstOrDefault(e => e.Value.HasTag(GAME_TAG.PLAYER_ID) && !e.Value.IsPlayer);

            if (player.Value != null)
            {
                Game.CurrentGameStats.PlayerName = player.Value.Name;
            }
            if (opponent.Value != null)
            {
                Game.CurrentGameStats.OpponentName = opponent.Value.Name;
            }

            Game.CurrentGameStats.Turns = HsLogReader.Instance.GetTurnNumber();
            if (Config.Instance.DiscardZeroTurnGame && Game.CurrentGameStats.Turns < 1)
            {
                Logger.WriteLine("Game has 0 turns, discarded. (DiscardZeroTurnGame)", "GameEventHandler");
                _assignedDeck = null;
                return;
            }
            Game.CurrentGameStats.GameEnd();
            var selectedDeck = Helper.MainWindow.DeckPickerList.GetSelectedDeckVersion();

            if (selectedDeck != null)
            {
                if (Config.Instance.DiscardGameIfIncorrectDeck &&
                    !Game.PlayerDrawn.All(
                        c =>
                        c.IsStolen ||
                        selectedDeck.GetSelectedDeckVersion().Cards.Any(c2 => c.Id == c2.Id && c.Count <= c2.Count)))
                {
                    Logger.WriteLine("Assigned current game to NO deck - selected deck does not match cards played", "GameEventHandler");
                    Game.CurrentGameStats.DeleteGameFile();
                    _assignedDeck = null;
                    return;
                }
                Game.CurrentGameStats.PlayerDeckVersion        = selectedDeck.Version;
                Game.CurrentGameStats.HearthStatsDeckVersionId = selectedDeck.HearthStatsDeckVersionId;

                _lastGame = Game.CurrentGameStats;
                selectedDeck.DeckStats.AddGameResult(_lastGame);
                if (Config.Instance.ShowNoteDialogAfterGame && !Config.Instance.NoteDialogDelayed && !_showedNoteDialog)
                {
                    _showedNoteDialog = true;
                    new NoteDialog(Game.CurrentGameStats);
                }
                Logger.WriteLine("Assigned current game to deck: " + selectedDeck.Name, "GameStats");
                _assignedDeck = selectedDeck;

                if (HearthStatsAPI.IsLoggedIn && Config.Instance.HearthStatsAutoUploadNewGames)
                {
                    if (Game.CurrentGameMode == GameMode.None)
                    {
                        await GameModeDetection(300);                         //give the user 5 minutes to get out of the victory/defeat screen
                    }
                    if (Game.CurrentGameMode == GameMode.Casual)
                    {
                        await HsLogReader.Instance.RankedDetection();
                    }
                    if (Game.CurrentGameMode == GameMode.Ranked && !_lastGame.HasRank)
                    {
                        await RankDetection(5);
                    }
                    await GameModeSaved(15);

                    if (Game.CurrentGameMode == GameMode.Arena)
                    {
                        HearthStatsManager.UploadArenaMatchAsync(_lastGame, selectedDeck, background: true);
                    }
                    else
                    {
                        HearthStatsManager.UploadMatchAsync(_lastGame, selectedDeck, background: true);
                    }
                }
                _lastGame = null;
            }
            else
            {
                DefaultDeckStats.Instance.GetDeckStats(Game.PlayingAs).AddGameResult(Game.CurrentGameStats);
                Logger.WriteLine(string.Format("Assigned current deck to default {0} deck.", Game.PlayingAs), "GameStats");
                _assignedDeck = null;
            }
        }
        internal static async void UpdateAsync()
        {
            const string url = "https://raw.githubusercontent.com/Epix37/HDT-Data/master/news";

            _update              = true;
            _lastNewsCheck       = DateTime.MinValue;
            _lastNewsUpdate      = DateTime.MinValue;
            CurrentNewsId        = Config.Instance.IgnoreNewsId;
            _lastHearthStatsSync = DateTime.Now;
            while (_update)
            {
                if ((DateTime.Now - _lastNewsCheck) > TimeSpan.FromSeconds(NewsCheckInterval))
                {
                    try
                    {
                        var oldNewsId = CurrentNewsId;
                        using (var client = new WebClient())
                        {
                            var raw = await client.DownloadStringTaskAsync(url);

                            var content =
                                raw.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Select(
                                    x => x.Trim()).ToArray();
                            try
                            {
                                CurrentNewsId = int.Parse(content[0].Split(':')[1].Trim());
                            }
                            catch (Exception)
                            {
                                CurrentNewsId = 0;
                            }
                            _news = content.Skip(1).ToArray();
                        }
                        if (CurrentNewsId > oldNewsId ||
                            Core.MainWindow.StatusBarNews.Visibility == Visibility.Collapsed &&
                            CurrentNewsId > Config.Instance.IgnoreNewsId)
                        {
                            Core.MainWindow.TopRow.Height            = new GridLength(26);
                            Core.MainWindow.StatusBarNews.Visibility = Visibility.Visible;
                            Core.MainWindow.MinHeight += Core.MainWindow.StatusBarNewsHeight;
                            UpdateNews(0);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.WriteLine("Error loading news: " + e, "UpdateNews");
                    }
                    _lastNewsCheck = DateTime.Now;
                }
                if ((DateTime.Now - _lastNewsUpdate) > TimeSpan.FromSeconds(NewsTickerUpdateInterval))
                {
                    UpdateNews();
                }

                if (HearthStatsAPI.IsLoggedIn && Config.Instance.HearthStatsAutoSyncInBackground &&
                    (DateTime.Now - _lastHearthStatsSync) > TimeSpan.FromSeconds(HearthStatsAutoSyncInterval))
                {
                    _lastHearthStatsSync = DateTime.Now;
                    HearthStatsManager.SyncAsync(background: true);
                }
                await Task.Delay(1000);
            }
        }