public QueuePopOverlay(GameDTO InitialDTO)
 {
     InitializeComponent();
     Client.IsInGame = true;
     Client.FocusClient();
     InitializePop(InitialDTO);
     TimeLeft = InitialDTO.JoinTimerDuration;
     Client.RtmpConnection.MessageReceived += OnMessageReceived;
     QueueTimer = new System.Timers.Timer(1000);
     QueueTimer.Elapsed += new ElapsedEventHandler(QueueElapsed);
     QueueTimer.Enabled = true;
 }
        public QueuePopOverlay(GameDTO InitialDTO, Page previousPage)
        {
            if (InitialDTO == null)
                return;

            InitializeComponent();
            Client.FocusClient();
            InitializePop(InitialDTO);
            this.previousPage = previousPage;
            page = new ChampSelectPage(InitialDTO.RoomName, InitialDTO.RoomPassword);
            TimeLeft = InitialDTO.JoinTimerDuration;
            Client.RiotConnection.MessageReceived += PVPNet_OnMessageReceived;
            QueueTimer = new Timer(1000);
            QueueTimer.Elapsed += QueueElapsed;
            QueueTimer.Enabled = true;
            Client.MainWin.FlashWindow();
            if (!Properties.Settings.Default.DisableClientSound)
                QueuePopSound.PlayQueuePopSound();
        }
 public CustomGameLobbyPage(GameDTO gameLobby = null)
 {
     InitializeComponent();
     //Hopefully this works better
     foreach (var champs in Client.PlayerChampions.Where(champs => champs.BotEnabled))
         bots.Add(champs.ChampionId);
     GameName.Content = Client.GameName;
     Client.RiotConnection.MessageReceived += GameLobby_OnMessageReceived;
     //If client has created game use initial DTO
     if (Client.GameLobbyDTO != null)
         Lobby_OnMessageReceived(null, Client.GameLobbyDTO);
     else
     {
         Client.GameLobbyDTO = gameLobby;
         Lobby_OnMessageReceived(null, Client.GameLobbyDTO);
     }
     Client.InviteListView = InviteListView;
     Client.CurrentPage = this;
     Client.ReturnButton.Visibility = Visibility.Visible;
     Client.ReturnButton.Content = "Return to Custom Game Lobby";
 }
        /// <summary>
        ///     Main logic behind Champion Select
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="message"></param>
        private void Select_OnMessageReceived(object sender, object message)
        {
            if (message is GameDTO)
            {
                #region In Champion Select

                var champDto = message as GameDTO;
                //Sometimes chat doesn't work so spam this until it does
                LatestDto = champDto;
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async () =>
                {
                    //Allow all champions to be selected (reset our modifications)
                    var championArray = new ListViewItem[ChampionSelectListView.Items.Count];
                    ChampionSelectListView.Items.CopyTo(championArray, 0);
                    foreach (ListViewItem y in championArray)
                    {
                        y.IsHitTestVisible = true;
                        y.Opacity = 1;
                    }

                    //Push all teams into one array to save a foreach call (looks messy)
                    if (champDto == null)
                        return;

                    var allParticipants = new List<Participant>(champDto.TeamOne.ToArray());
                    allParticipants.AddRange(champDto.TeamTwo);

                    int t = 1;

                    if (LatestDto.QueueTypeName == "COUNTER_PICK") //fix for nemesis draft, get your champ from GameDTO
                    {
                        var selectedChamp = champDto.PlayerChampionSelections.Find(item => item.SummonerInternalName == Client.LoginPacket.AllSummonerData.Summoner.InternalName);
                        ChangeSelectedChampionSkins(selectedChamp.ChampionId);
                    }
                    foreach (PlayerParticipant participant in allParticipants.Select(p => p as PlayerParticipant))
                    {
                        if (participant != null)
                        {
                            PlayerParticipant play = participant;
                            //If it is our turn to pick
                            if (play.PickTurn == champDto.PickTurn)
                            {
                                if (play.SummonerId == Client.LoginPacket.AllSummonerData.Summoner.SumId)
                                {
                                    if (Settings.Default.PickBanFocus)
                                        Client.MainWin.Focus();
                                    if (Settings.Default.PickBanFlash)
                                        Client.MainWin.FlashWindow();
                                    //Allows us to instapick any champ we own. 
                                    if (Client.usingInstaPick)
                                    {
                                        bool champbanned = false;
                                        //disallow picking banned champs
                                        try
                                        {
                                            foreach (
                                                BannedChampion x in
                                                    champDto.BannedChampions.Where(
                                                        x => x.ChampionId == Client.SelectChamp))
                                                champbanned = true;

                                            //disallow picking picked champs
                                            foreach (
                                                PlayerChampionSelectionDTO selection in
                                                    champDto.PlayerChampionSelections.Where(
                                                        selection => selection.ChampionId == Client.SelectChamp))
                                                champbanned = true;

                                            var temp = new ListViewItem
                                            {
                                                Tag = Client.SelectChamp
                                            };
                                            if (!champbanned)
                                                ListViewItem_PreviewMouseDown(temp, null);

                                            Client.usingInstaPick = false;
                                        }
                                        catch
                                        {
                                            Client.Log("Something went weird insta-picking a champ", "Error");
                                        }
                                    }

                                    ChampionSelectListView.IsHitTestVisible = true;

                                    ChampionSelectListView.Opacity = 1;
                                    GameStatusLabel.Content = "Your turn to pick!";
                                    break;
                                }
                            }
                            if (string.IsNullOrEmpty(participant.SummonerName))
                            {
                                participant.SummonerName = "Summoner " + t;
                                t++;
                            }
                        }
                        //Otherwise block selection of champions unless in dev mode
                        if (!Client.Dev)
                        {
                            ChampionSelectListView.IsHitTestVisible = false;
                            ChampionSelectListView.Opacity = 0.5;
                        }
                        GameStatusLabel.Content = "Waiting for others to pick...";
                    }

                    allParticipants = allParticipants.Distinct().ToList();

                    //Champion select was cancelled 
                    if (champDto.GameState == "TEAM_SELECT")
                    {
                        if (CountdownTimer != null)
                            CountdownTimer.Stop();

                        Client.FixChampSelect();

                        return;
                    }
                    if (champDto.GameState == "PRE_CHAMP_SELECT")
                    {
                        //Banning phase. Enable banning phase and this will render only champions for ban
                        BanningPhase = true;
                        PurpleBansLabel.Visibility = Visibility.Visible;
                        BlueBansLabel.Visibility = Visibility.Visible;
                        BlueBanListView.Visibility = Visibility.Visible;
                        PurpleBanListView.Visibility = Visibility.Visible;
                        GameStatusLabel.Content = "Bans are on-going";
                        counter = configType.BanTimerDuration - 3;

                        #region Render Bans

                        BlueBanListView.Items.Clear();
                        PurpleBanListView.Items.Clear();
                        foreach (BannedChampion x in champDto.BannedChampions)
                        {
                            var champImage = new Image
                            {
                                Height = 58,
                                Width = 58,
                                Source = champions.GetChampion(x.ChampionId).icon
                            };
                            if (x.TeamId == 100)
                                BlueBanListView.Items.Add(champImage);
                            else
                                PurpleBanListView.Items.Add(champImage);

                            foreach (var y in championArray.Where(y => (int)y.Tag == x.ChampionId))
                            {
                                ChampionSelectListView.Items.Remove(y);
                                //Remove from arrays
                                foreach (
                                    ChampionDTO playerChamps in
                                        ChampList.ToArray()
                                            .Where(playerChamps => x.ChampionId == playerChamps.ChampionId))
                                {
                                    ChampList.Remove(playerChamps);

                                    break;
                                }

                                foreach (
                                    ChampionBanInfoDTO banChamps in
                                        ChampionsForBan.ToArray()
                                            .Where(banChamps => x.ChampionId == banChamps.ChampionId))
                                {
                                    ChampionsForBan.Remove(banChamps);

                                    break;
                                }
                            }
                        }

                        #endregion Render Bans
                    }
                    else if (champDto.GameState == "CHAMP_SELECT")
                    {
                        //Picking has started. If pickturn has changed reset timer
                        LastPickTurn = champDto.PickTurn;
                        BanningPhase = false;
                    }
                    else if (champDto.GameState == "POST_CHAMP_SELECT")
                    {
                        //Post game has started. Allow trading
                        CanTradeWith = await RiotCalls.GetPotentialTraders();
                        HasLockedIn = true;
                        GameStatusLabel.Content = "All players have picked!";
                        if (configType != null)
                            counter = configType.PostPickTimerDuration - 2;
                        else
                            counter = 10;
                    }
                    else if (champDto.GameState == "START_REQUESTED")
                    {
                        GameStatusLabel.Content = "The game is about to start!";
                        DodgeButton.IsEnabled = false; //Cannot dodge past this point!
                        counter = 1;
                    }
                    else if (champDto.GameState == "TERMINATED")
                    {
                        var pop = new NotifyPlayerPopup("Player Dodged", "Player has Dodged Queue.")
                        {
                            HorizontalAlignment = HorizontalAlignment.Right,
                            VerticalAlignment = VerticalAlignment.Bottom
                        };
                        Client.CurrentPage = previousPage;
                        Client.HasPopped = false;
                        Client.ReturnButton.Content = "Return to Lobby Page";
                        Client.ReturnButton.Visibility = Visibility.Visible;
                        Client.inQueueTimer.Visibility = Visibility.Visible;
                        Client.NotificationGrid.Children.Add(pop);
                        Client.RiotConnection.MessageReceived -= ChampSelect_OnMessageReceived;
                        //Client.OnFixChampSelect -= ChampSelect_OnMessageReceived;
                        Client.GameStatus = "inQueue";
                        Client.SetChatHover();
                        Client.SwitchPage(previousPage);
                        Client.ClearPage(typeof(ChampSelectPage));

                    }

                    #region Display players

                    BlueListView.Items.Clear();
                    PurpleListView.Items.Clear();
                    BlueListView.Items.Refresh();
                    PurpleListView.Items.Refresh();
                    int i = 0;
                    bool purpleSide = false;

                    //Aram hack, view other players champions & names (thanks to Andrew)
                    var otherPlayers = new List<PlayerChampionSelectionDTO>(champDto.PlayerChampionSelections.ToArray());
                    AreWePurpleSide = false;

                    foreach (Participant participant in allParticipants)
                    {
                        Participant tempParticipant = participant;
                        i++;
                        var control = new ChampSelectPlayer();
                        //Cast AramPlayers as PlayerParticipants. This removes reroll data
                        if (tempParticipant is AramPlayerParticipant)
                        {
                            tempParticipant = (PlayerParticipant)tempParticipant;
                        }

                        if (tempParticipant is PlayerParticipant)
                        {
                            var player = tempParticipant as PlayerParticipant;
                            if (!string.IsNullOrEmpty(player.SummonerName))
                            {
                                control.PlayerName.Content = player.SummonerName;
                                control.sumName = player.SummonerName;
                            }
                            else
                            {
                                try
                                {
                                    AllPublicSummonerDataDTO summoner =
                                        await RiotCalls.GetAllPublicSummonerDataByAccount(player.SummonerId);
                                    if (summoner.Summoner != null && !string.IsNullOrEmpty(summoner.Summoner.Name))
                                        control.PlayerName.Content = summoner.Summoner.Name;
                                    else
                                        control.PlayerName.Content = "Unknown Player";
                                }
                                catch
                                {
                                    control.PlayerName.Content = "Unknown Player";
                                }
                            }

                            foreach (PlayerChampionSelectionDTO selection in champDto.PlayerChampionSelections)
                            {
                                #region Disable picking selected champs

                                PlayerChampionSelectionDTO selection1 = selection;
                                foreach (ListViewItem y in championArray.Where(y => (int)y.Tag == selection1.ChampionId))
                                {
                                    y.IsHitTestVisible = true;
                                    y.Opacity = 0.5;
                                    if (configType == null)
                                        continue;

                                    if (!configType.DuplicatePick)
                                        continue;

                                    y.IsHitTestVisible = false;
                                    y.Opacity = 1;
                                }

                                foreach (ListViewItem y in championArray.Where(y => disabledCharacters.Contains((int)y.Tag)))
                                {
                                    y.Opacity = .7;
                                    y.IsHitTestVisible = false;
                                }

                                #endregion Disable picking selected champs

                                if (selection.SummonerInternalName != player.SummonerInternalName)
                                    continue;

                                //Clear our teams champion selection for aram hack
                                otherPlayers.Remove(selection);
                                control = RenderPlayer(selection, player);
                                //If we have locked in render skin select
                                if (!HasLockedIn ||
                                    selection.SummonerInternalName !=
                                    Client.LoginPacket.AllSummonerData.Summoner.InternalName || (Client.Dev && champDto.MapId != 12))
                                    continue;

                                if (purpleSide)
                                    AreWePurpleSide = true;

                                RenderLockInGrid(selection);
                                if (player.PointSummary == null)
                                    continue;

                                LockInButton.Content = string.Format("Reroll ({0}/{1})",
                                    player.PointSummary.CurrentPoints, player.PointSummary.PointsCostToRoll);
                                LockInButton.IsEnabled = player.PointSummary.NumberOfRolls > 0;
                            }
                        }
                        else if (tempParticipant is ObfuscatedParticipant)
                        {
                            control.PlayerName.Content = "Summoner " +
                                                         ((tempParticipant as ObfuscatedParticipant).GameUniqueId -
                                                          ((tempParticipant as ObfuscatedParticipant).GameUniqueId > 5
                                                              ? 5
                                                              : 0));
                        }
                        else if (tempParticipant is BotParticipant)
                        {
                            var bot = tempParticipant as BotParticipant;
                            if (bot.SummonerInternalName.Contains('_'))
                            {
                                string botChamp = bot.SummonerInternalName.Split('_')[1]; //Why is this internal name rito?
                                champions botSelectedChamp = champions.GetChampion(botChamp);
                                var part = new PlayerParticipant();
                                var selection = new PlayerChampionSelectionDTO
                                {
                                    ChampionId = botSelectedChamp.id
                                };
                                part.SummonerName = botSelectedChamp.displayName + " bot";
                                control = RenderPlayer(selection, part);
                            }
                            else
                            {
                                control.PlayerName.Content = "Bot";
                                control.sumName = "Bot";
                            }
                        }
                        else
                            control.PlayerName.Content = "Unknown Summoner";

                        //Display purple side if we have gone through our team
                        if (i > champDto.TeamOne.Count)
                        {
                            i = 0;
                            purpleSide = true;
                        }

                        if (!purpleSide)
                            BlueListView.Items.Add(control);
                        else
                            PurpleListView.Items.Add(control);
                    }

                    //Do aram hack!
                    if (otherPlayers.Count <= 0)
                        return;

                    if (AreWePurpleSide)
                        BlueListView.Items.Clear();
                    else
                        PurpleListView.Items.Clear();

                    foreach (PlayerChampionSelectionDTO hackSelection in otherPlayers)
                    {
                        var player = new PlayerParticipant
                        {
                            SummonerName = hackSelection.SummonerInternalName
                        };
                        ChampSelectPlayer control = RenderPlayer(hackSelection, player);
                        if (AreWePurpleSide)
                            BlueListView.Items.Add(control);
                        else
                            PurpleListView.Items.Add(control);
                    }

                    #endregion Display players
                }));

                #endregion In Champion Select
            }
            else if (message is PlayerCredentialsDto)
            {
                Client.RiotConnection.MessageReceived -= ChampSelect_OnMessageReceived;

                #region Launching Game

                var dto = message as PlayerCredentialsDto;
                Client.CurrentGame = dto;

                if (HasLaunchedGame)
                    return;

                HasLaunchedGame = true;


                if (Settings.Default.AutoRecordGames)
                {
                    Dispatcher.InvokeAsync(async () =>
                    {
                        PlatformGameLifecycleDTO n =
                            await
                                RiotCalls.RetrieveInProgressSpectatorGameInfo(
                                    Client.LoginPacket.AllSummonerData.Summoner.Name);
                        if (n.GameName != null)
                        {
                            string ip = n.PlayerCredentials.ObserverServerIp + ":" +
                                        n.PlayerCredentials.ObserverServerPort;
                            string key = n.PlayerCredentials.ObserverEncryptionKey;
                            var gameId = (int)n.PlayerCredentials.GameId;
                            new ReplayRecorder(ip, gameId, Client.Region.InternalName, key);
                        }
                    });
                }
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    if (CountdownTimer != null)
                        CountdownTimer.Stop();

                    InGame();
                    Client.ReturnButton.Visibility = Visibility.Hidden;
                    if (!Settings.Default.DisableClientSound)
                    {
                        Client.AmbientSoundPlayer.Stop();
                    }
                }));

                #endregion Launching Game
            }
            else if (message is TradeContractDTO)
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    var tradeDto = message as TradeContractDTO;
                    if (tradeDto == null)
                        return;

                    switch (tradeDto.State)
                    {
                        case "PENDING":
                            {
                                PlayerTradeControl.Visibility = Visibility.Visible;
                                PlayerTradeControl.Tag = tradeDto;
                                PlayerTradeControl.AcceptButton.Visibility = Visibility.Visible;
                                PlayerTradeControl.DeclineButton.Content = "Decline";

                                champions myChampion = champions.GetChampion((int)tradeDto.ResponderChampionId);
                                PlayerTradeControl.MyChampImage.Source = myChampion.icon;
                                PlayerTradeControl.MyChampLabel.Content = myChampion.displayName;
                                champions theirChampion = champions.GetChampion((int)tradeDto.RequesterChampionId);
                                PlayerTradeControl.TheirChampImage.Source = theirChampion.icon;
                                PlayerTradeControl.TheirChampLabel.Content = theirChampion.displayName;
                                PlayerTradeControl.RequestLabel.Content = string.Format("{0} wants to trade!",
                                    tradeDto.RequesterInternalSummonerName);
                            }
                            break;
                        case "BUSY":
                        case "DECLINED":
                        case "CANCELED":
                            {
                                PlayerTradeControl.Visibility = Visibility.Hidden;

                                TextInfo text = new CultureInfo("en-US", false).TextInfo;
                                var pop = new NotificationPopup(ChatSubjects.INVITE_STATUS_CHANGED,
                                    string.Format("{0} has {1} this trade", tradeDto.RequesterInternalSummonerName,
                                        text.ToTitleCase(tradeDto.State)));

                                if (tradeDto.State == "BUSY")
                                    pop.NotificationTextBox.Text = string.Format("{0} is currently busy",
                                        tradeDto.RequesterInternalSummonerName);

                                pop.Height = 200;
                                pop.OkButton.Visibility = Visibility.Visible;
                                pop.HorizontalAlignment = HorizontalAlignment.Right;
                                pop.VerticalAlignment = VerticalAlignment.Bottom;
                                Client.NotificationGrid.Children.Add(pop); //*/
                            }
                            break;
                    }
                }));
            }
        }
        private async void StartChampSelect()
        {
            //Force client to popup once in champion select
            Client.FocusClient();
            //Get champions and sort alphabetically

            CanLockIn = false;
            ChampList = new List<ChampionDTO>(Client.PlayerChampions);
            ChampList.Sort(
                (x, y) =>
                    string.Compare(champions.GetChampion(x.ChampionId)
                        .displayName, champions.GetChampion(y.ChampionId).displayName, StringComparison.Ordinal));
            if (Client.LoginPacket.ClientSystemStates.freeToPlayChampionsForNewPlayersMaxLevel >=
                Client.LoginPacket.AllSummonerData.SummonerLevel.Level)
                foreach (var item in ChampList)
                {
                    if (Client.LoginPacket.ClientSystemStates.freeToPlayChampionIdList.Contains(item.ChampionId))
                        item.FreeToPlay = true;
                    else
                        item.FreeToPlay = false;
                }

            //Retrieve masteries and runes
            MyMasteries = Client.LoginPacket.AllSummonerData.MasteryBook;
            MyRunes = Client.LoginPacket.AllSummonerData.SpellBook;

            //Put masteries & runes into combo boxes
            int i = 0;
            foreach (MasteryBookPageDTO masteryPage in MyMasteries.BookPages)
            {
                string masteryPageName = masteryPage.Name;
                //Stop garbage mastery names
                if (masteryPageName.StartsWith("@@"))
                    masteryPageName = "Mastery Page " + ++i;

                MasteryComboBox.Items.Add(masteryPageName);
                if (masteryPage.Current)
                    MasteryComboBox.SelectedValue = masteryPageName;
            }
            i = 0;
            foreach (SpellBookPageDTO runePage in MyRunes.BookPages)
            {
                string runePageName = runePage.Name;
                //Stop garbage rune names
                if (runePageName.StartsWith("@@"))
                    runePageName = "Rune Page " + ++i;

                RuneComboBox.Items.Add(runePageName);
                if (runePage.Current)
                    RuneComboBox.SelectedValue = runePageName;
            }
            //Allow runes & masteries to be changed
            QuickLoad = true;

            //Signal to the server we are in champion select
            await RiotCalls.SetClientReceivedGameMessage(Client.GameID, "CHAMP_SELECT_CLIENT");
            GameDTO latestDto =
                await
                    RiotCalls.GetLatestGameTimerState(Client.GameID, Client.ChampSelectDTO.GameState,
                        Client.ChampSelectDTO.PickTurn);
            //Find the game config for timers
            configType = Client.LoginPacket.GameTypeConfigs.Find(x => x.Id == latestDto.GameTypeConfigId);
            if (configType == null) //Invalid config... abort!
            {
                QuitCurrentGame();

                var overlay = new MessageOverlay
                {
                    MessageTextBox =
                    {
                        Text = "Invalid Config ID (" + latestDto.GameTypeConfigId +
                               "). Report to Eddy5641 [https://github.com/Eddy5641/LegendaryClient/issues/new]"
                    },
                    MessageTitle = { Content = "Invalid Config" }
                };
                Client.OverlayContainer.Content = overlay.Content;
                Client.OverlayContainer.Visibility = Visibility.Visible;
            }
            else
            {
                counter = configType.MainPickTimerDuration - 5;
                //Seems to be a 5 second inconsistancy with riot and what they actually provide
                CountdownTimer = new Timer();
                CountdownTimer.Tick += CountdownTimer_Tick;
                CountdownTimer.Interval = 1000; // 1 second
                CountdownTimer.Start();

                LatestDto = latestDto;
                //Get the champions for the other team to ban & sort alpabetically
                if (latestDto.GameState.ToUpper() == "PRE_CHAMP_SELECT")
                {
                    ChampionBanInfoDTO[] champsForBan = await RiotCalls.GetChampionsForBan();
                    ChampionsForBan = new List<ChampionBanInfoDTO>(champsForBan);
                    ChampionsForBan.Sort(
                        (x, y) =>
                            string.Compare(champions.GetChampion(x.ChampionId)
                                .displayName, champions.GetChampion(y.ChampionId).displayName, StringComparison.Ordinal));
                }


                //Render our champions
                RenderChamps(false);

                //Start recieving champ select
                Select_OnMessageReceived(this, latestDto);
                //Client.OnFixChampSelect += ChampSelect_OnMessageReceived;
                Client.RiotConnection.MessageReceived += ChampSelect_OnMessageReceived;
            }
        }
 private void CreatedGame(GameDTO result)
 {
     Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
     {
         if (result.Name == null)
         {
             NameInvalidLabel.Visibility = Visibility.Visible;
             NameInvalidLabel.Content = "Name is already taken!";
         }
         else
         {
             Client.InGame = true;
             Client.GameID = result.Id;
             Client.GameName = result.Name;
             Client.GameLobbyDTO = result;
             Client.SwitchPage(new CustomGameLobbyPage());
         }
     }));
 }
        private void PVPNet_OnMessageReceived(object sender, object msg)
        {
            var args = msg as MessageReceivedEventArgs;
            var message = args != null ? args.Body : msg;
            if (!(message is InvitationRequest))
                return;

            if (message.GetType() == typeof(InvitationRequest))
            {
                var stats = (InvitationRequest)message;
                try
                {
                    var info = Client.InviteData[stats.InvitationId];
                    //Data about this popup has changed. We want to set this
                    if (!Equals(info.popup, this))
                        return;

                    switch (stats.InvitationState)
                    {
                        case "ON_HOLD":
                            NotificationTextBox.Text = string.Format("The invite from {0} is now on hold",
                                info.Inviter);
                            Lockup();
                            Visibility = Visibility.Hidden;
                            break;
                        case "TERMINATED":
                            NotificationTextBox.Text = string.Format("The invite from {0} has been terminated",
                                info.Inviter);
                            Lockup();
                            Visibility = Visibility.Hidden;
                            break;
                        case "REVOKED":
                            NotificationTextBox.Text = string.Format("The invite from {0} has timed out", info.Inviter);
                            Lockup();
                            Visibility = Visibility.Hidden;
                            break;
                        case "ACTIVE":
                            NotificationTextBox.Text = "";
                            LoadGamePopupData(stats.Inviter == null ? info.stats : stats);
                            Visibility = Visibility.Hidden;

                            RenderNotificationTextBox(inviter + " has invited you to a game");
                            RenderNotificationTextBox("");
                            RenderNotificationTextBox("Mode: " + mode);
                            RenderNotificationTextBox("Map: " + mapName);
                            RenderNotificationTextBox("Type: " + type);
                            Unlock();
                            break;
                        default:
                            NotificationTextBox.Text = string.Format("The invite from {0} is now {1}", info.Inviter,
                                Client.TitleCaseString(stats.InvitationState));
                            Lockup();
                            break;
                    }
                }
                catch (Exception)
                {
                    //We do not need this popup. it is a new one. Let it launch
                }
            }
            else if (message.GetType() == typeof (GameDTO))
            {
                tempDTO = (GameDTO)message;
            }
        }
        public async void InitializePop(GameDTO InitialDTO)
        {
            List<Participant> allParticipants = InitialDTO.TeamOne;
            allParticipants.AddRange(InitialDTO.TeamTwo);
            if (InitialDTO.TeamOne[0] is ObfuscatedParticipant)
                ReverseString = true;

            allParticipants = allParticipants.Distinct().ToList();
            //Seems to have fixed the queuepopoverlay page crashing.
            //whichever team you're on sometimes duplicates and could not find a reason as it doesn't happen a lot.
            int i = 1;
            foreach (Participant p in allParticipants)
            {
                var player = new QueuePopPlayer
                {
                    Width = 264,
                    Height = 70
                };
                var part = p as PlayerParticipant;
                if (part != null)
                {
                    PlayerParticipant playerPart = part;
                    if (!string.IsNullOrEmpty(playerPart.SummonerName))
                    {
                        player.PlayerLabel.Content = playerPart.SummonerName;
                        player.RankLabel.Content = "";
                        player.Tag = part;
                        Team1ListBox.Items.Add(player);
                    }
                    else
                    {
                        Client.Log(playerPart.SummonerId.ToString(CultureInfo.InvariantCulture));
                        player.PlayerLabel.Content = "Summoner " + i;
                        i++;
                        player.RankLabel.Content = "";
                        Team2ListBox.Items.Add(player);
                    }
                }
                else
                {
                    var oPlayer = p as ObfuscatedParticipant;
                    if (oPlayer != null)
                        player.PlayerLabel.Content = "Summoner " +
                                                     (oPlayer.GameUniqueId - (oPlayer.GameUniqueId > 5 ? 5 : 0));
                    player.RankLabel.Content = "";
                    Team2ListBox.Items.Add(player);
                }
            }
            GetPlayerLeagues();
            if (!Client.AutoAcceptQueue)
                return;

            await RiotCalls.AcceptPoppedGame(true);
            accepted = true;
            
        }
        /// <summary>
        /// Initializes all data required for champion select. Also retrieves latest GameDTO
        /// </summary>
        private async void StartChampSelect()
        {
            //Force client to popup once in champion select
            Client.FocusClient();
            Client.IsInGame = true;
            //Get champions and sort first by favourite, then alphabetically
            ChampList = new List<ChampionDTO>(Client.PlayerChampions);
            ChampList.Sort(delegate(ChampionDTO x, ChampionDTO y)
            {
                int IsFav = champions.GetChampion(y.ChampionId).IsFavourite.CompareTo(champions.GetChampion(x.ChampionId).IsFavourite);
                if (IsFav != 0) return IsFav;
                else return champions.GetChampion(x.ChampionId).displayName.CompareTo(champions.GetChampion(y.ChampionId).displayName);
            });

            //Retrieve masteries and runes
            MyMasteries = Client.LoginPacket.AllSummonerData.MasteryBook;
            MyRunes = Client.LoginPacket.AllSummonerData.SpellBook;

            //Put masteries & runes into combo boxes
            int i = 0;
            foreach (MasteryBookPageDTO MasteryPage in MyMasteries.BookPages)
            {
                string MasteryPageName = MasteryPage.Name;
                //Stop garbage mastery names
                if (MasteryPageName.StartsWith("@@")) 
                {
                    MasteryPageName = "Mastery Page " + ++i;
                }
                MasteryComboBox.Items.Add(MasteryPageName);
                if (MasteryPage.Current)
                    MasteryComboBox.SelectedValue = MasteryPageName;
            }
            i = 0;
            foreach (SpellBookPageDTO RunePage in MyRunes.BookPages)
            {
                string RunePageName = RunePage.Name;
                //Stop garbage rune names
                if (RunePageName.StartsWith("@@"))
                {
                    RunePageName = "Rune Page " + ++i;
                }
                RuneComboBox.Items.Add(RunePageName);
                if (RunePage.Current)
                    RuneComboBox.SelectedValue = RunePageName;
            }
            //Allow runes & masteries to be changed
            QuickLoad = true;

            //Signal to the server we are in champion select
            await RiotCalls.SetClientReceivedGameMessage(Client.GameID, "CHAMP_SELECT_CLIENT");
            //Retrieve the latest GameDTO
            GameDTO latestDTO = await RiotCalls.GetLatestGameTimerState(Client.GameID, Client.ChampSelectDTO.GameState, Client.ChampSelectDTO.PickTurn);
            //Find the game config for timers
            configType = Client.LoginPacket.GameTypeConfigs.Find(x => x.Id == latestDTO.GameTypeConfigId);
            if (configType == null) //Invalid config... abort!
            {
                Client.QuitCurrentGame();

                MessageOverlay overlay = new MessageOverlay();
                overlay.MessageTextBox.Text = "Invalid Config ID (" + latestDTO.GameTypeConfigId.ToString() + "). Report to Snowl [https://github.com/Snowl/LegendaryClient/issues/new]";
                overlay.MessageTitle.Content = "Invalid Config";
                Client.OverlayContainer.Content = overlay.Content;
                Client.OverlayContainer.Visibility = Visibility.Visible;
                return;
            }
            counter = configType.MainPickTimerDuration - 5; //Seems to be a 5 second inconsistancy with riot and what they actually provide
            CountdownTimer = new System.Windows.Forms.Timer();
            CountdownTimer.Tick += new EventHandler(CountdownTimer_Tick);
            CountdownTimer.Interval = 1000; // 1 second
            CountdownTimer.Start();

            LatestDto = latestDTO;
            //Get the champions for the other team to ban & sort alpabetically
            ChampionBanInfoDTO[] ChampsForBan = await RiotCalls.GetChampionsForBan();
            ChampionsForBan = new List<ChampionBanInfoDTO>(ChampsForBan);
            ChampionsForBan.Sort((x, y) => champions.GetChampion(x.ChampionId).displayName.CompareTo(champions.GetChampion(y.ChampionId).displayName));

            //Join champion select chatroom
            string JID = Client.GetChatroomJID(latestDTO.RoomName.Replace("@sec", ""), latestDTO.RoomPassword, false);
            Chatroom = Client.ConfManager.GetRoom(new jabber.JID(JID));
            Chatroom.Nickname = Client.LoginPacket.AllSummonerData.Summoner.Name;
            Chatroom.OnRoomMessage += Chatroom_OnRoomMessage;
            Chatroom.OnParticipantJoin += Chatroom_OnParticipantJoin;
            Chatroom.Join(latestDTO.RoomPassword);

            //Render our champions
            RenderChamps(false);

            //Start recieving champ select
            ChampSelect_OnMessageReceived(this, latestDTO);
            Client.OnFixChampSelect += ChampSelect_OnMessageReceived;
            Client.RtmpConnection.MessageReceived += ChampSelect_OnMessageReceived;
        }
        /// <summary>
        /// Main logic behind Champion Select
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="message"></param>
        private void ChampSelect_OnMessageReceived(object sender, object message)
        {
            if (message.GetType() == typeof(GameDTO) || ((MessageReceivedEventArgs)message).Body.GetType() == typeof(GameDTO))
            {
                #region In Champion Select

                GameDTO ChampDTO = null;

                if (message.GetType() == typeof(GameDTO))
                    ChampDTO = message as GameDTO;
                else
                    ChampDTO = ((MessageReceivedEventArgs)message).Body as GameDTO;

                LatestDto = ChampDTO;
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async () =>
                {
                    //Allow all champions to be selected (reset our modifications)
                    ListViewItem[] ChampionArray = new ListViewItem[ChampionSelectListView.Items.Count];
                    ChampionSelectListView.Items.CopyTo(ChampionArray, 0);
                    foreach (ListViewItem y in ChampionArray)
                    {
                        y.IsHitTestVisible = true;
                        y.Opacity = 1;
                    }

                    //Push all teams into one array to save a foreach call (looks messy)
                    List<Participant> AllParticipants = new List<Participant>(ChampDTO.TeamOne.ToArray());
                    AllParticipants.AddRange(ChampDTO.TeamTwo);
                    foreach (Participant p in AllParticipants)
                    {
                        if (p is PlayerParticipant)
                        {
                            PlayerParticipant play = (PlayerParticipant)p;
                            //If it is our turn to pick
                            if (play.PickTurn == ChampDTO.PickTurn)
                            {
                                if (play.SummonerId == Client.LoginPacket.AllSummonerData.Summoner.SumId)
                                {
                                    ChampionSelectListView.IsHitTestVisible = true;
                                    ChampionSelectListView.Opacity = 1;
                                    GameStatusLabel.Content = "Your turn to pick!";
                                    break;
                                }
                            }
                        }
                        //Otherwise block selection of champions unless in dev mode
                        if (!DevMode)
                        {
                            ChampionSelectListView.IsHitTestVisible = false;
                            ChampionSelectListView.Opacity = 0.5;
                        }
                        GameStatusLabel.Content = "Waiting for others to pick...";
                    }

                    //Champion select was cancelled 
                    if (ChampDTO.GameState == "TEAM_SELECT")
                    {
                        if (CountdownTimer != null)
                        {
                            CountdownTimer.Stop();
                        }
                        Client.FixChampSelect();
                        CustomGameLobbyPage page = new CustomGameLobbyPage();
                        Client.GameLobbyDTO = ChampDTO;
                        Client.SwitchPage(page);
                        return;
                    }
                    else if (ChampDTO.GameState == "PRE_CHAMP_SELECT")
                    {
                        //Banning phase. Enable banning phase and this will render only champions for ban
                        BanningPhase = true;
                        PurpleBansLabel.Visibility = Visibility.Visible;
                        BlueBansLabel.Visibility = Visibility.Visible;
                        BlueBanListView.Visibility = Visibility.Visible;
                        PurpleBanListView.Visibility = Visibility.Visible;
                        GameStatusLabel.Content = "Bans are on-going";
                        counter = configType.BanTimerDuration - 3;

                        #region Render Bans
                        BlueBanListView.Items.Clear();
                        PurpleBanListView.Items.Clear();
                        foreach (var x in ChampDTO.BannedChampions)
                        {
                            Image champImage = new Image();
                            champImage.Height = 58;
                            champImage.Width = 58;
                            champImage.Source = champions.GetChampion(x.ChampionId).icon;
                            if (x.TeamId == 100)
                            {
                                BlueBanListView.Items.Add(champImage);
                            }
                            else
                            {
                                PurpleBanListView.Items.Add(champImage);
                            }

                            foreach (ListViewItem y in ChampionArray)
                            {
                                if ((int)y.Tag == x.ChampionId)
                                {
                                    ChampionSelectListView.Items.Remove(y);
                                    //Remove from arrays
                                    foreach (ChampionDTO PlayerChamps in ChampList.ToArray())
                                    {
                                        if (x.ChampionId == PlayerChamps.ChampionId)
                                        {
                                            ChampList.Remove(PlayerChamps);
                                            break;
                                        }
                                    }

                                    foreach (ChampionBanInfoDTO BanChamps in ChampionsForBan.ToArray())
                                    {
                                        if (x.ChampionId == BanChamps.ChampionId)
                                        {
                                            ChampionsForBan.Remove(BanChamps);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        #endregion Render Bans
                    }
                    else if (ChampDTO.GameState == "CHAMP_SELECT")
                    {
                        //Picking has started. If pickturn has changed reset timer
                        LastPickTurn = ChampDTO.PickTurn;
                        BanningPhase = false;
                    }
                    else if (ChampDTO.GameState == "POST_CHAMP_SELECT")
                    {
                        //Post game has started. Allow trading
                        CanTradeWith = await RiotCalls.GetPotentialTraders();
                        HasLockedIn = true;
                        GameStatusLabel.Content = "All players have picked!";
                        if (configType != null)
                            counter = configType.PostPickTimerDuration - 2;
                        else
                            counter = 10;
                    }
                    else if (ChampDTO.GameState == "START_REQUESTED")
                    {
                        GameStatusLabel.Content = "The game is about to start!";
                        DodgeButton.IsEnabled = false; //Cannot dodge past this point!
                        counter = 1;
                    }
                    else if (ChampDTO.GameState == "TERMINATED" || ChampDTO.GameState == "TERMINATED_IN_ERROR")
                    {
                        //TODO
                    }

                    #region Display players

                    BlueListView.Items.Clear();
                    PurpleListView.Items.Clear();
                    int i = 0;
                    bool PurpleSide = false;

                    //Aram hack, view other players champions & names (thanks to Andrew)
                    List<PlayerChampionSelectionDTO> OtherPlayers = new List<PlayerChampionSelectionDTO>(ChampDTO.PlayerChampionSelections.ToArray());
                    bool AreWePurpleSide = false;

                    foreach (Participant participant in AllParticipants)
                    {
                        Participant tempParticipant = participant;
                        i++;
                        ChampSelectPlayer control = new ChampSelectPlayer();
                       
                        if (tempParticipant is PlayerParticipant)
                        {
                            PlayerParticipant player = tempParticipant as PlayerParticipant;
                            control.PlayerName.Content = player.SummonerName;

                            foreach (PlayerChampionSelectionDTO selection in ChampDTO.PlayerChampionSelections)
                            {
                                #region Disable picking selected champs

                                foreach (ListViewItem y in ChampionArray)
                                {
                                    if ((int)y.Tag == selection.ChampionId)
                                    {
                                        y.IsHitTestVisible = false;
                                        y.Opacity = 0.5;
                                        if (configType != null)
                                        {
                                            if (configType.DuplicatePick)
                                            {
                                                y.IsHitTestVisible = true;
                                                y.Opacity = 1;
                                            }
                                        }
                                    }
                                }

                                #endregion Disable picking selected champs

                                if (selection.SummonerInternalName == player.SummonerInternalName)
                                {
                                    //Clear our teams champion selection for aram hack
                                    OtherPlayers.Remove(selection);
                                    control = RenderPlayer(selection, player);
                                    //If we have locked in render skin select
                                    if (HasLockedIn && selection.SummonerInternalName == Client.LoginPacket.AllSummonerData.Summoner.InternalName && !DevMode)
                                    {
                                        if (PurpleSide)
                                            AreWePurpleSide = true;
                                        RenderLockInGrid(selection);
                                        if (player.PointSummary != null)
                                        {
                                            LockInButton.Content = string.Format("Reroll ({0}/{1})", player.PointSummary.CurrentPoints, player.PointSummary.PointsCostToRoll);
                                            if (player.PointSummary.NumberOfRolls > 0)
                                                LockInButton.IsEnabled = true;
                                            else
                                                LockInButton.IsEnabled = false;
                                        }
                                    }
                                }
                            }
                        }
                        else if (tempParticipant is ObfuscatedParticipant)
                        {
                            control.PlayerName.Content = "Summoner " + i;
                        }
                        else if (tempParticipant is BotParticipant)
                        {
                            BotParticipant bot = tempParticipant as BotParticipant;
                            string botChamp = bot.SummonerName.Split(' ')[0]; //Why is this internal name rito?
                            champions botSelectedChamp = champions.GetChampion(botChamp);
                            PlayerParticipant part = new PlayerParticipant();
                            PlayerChampionSelectionDTO selection = new PlayerChampionSelectionDTO();
                            selection.ChampionId = botSelectedChamp.id;
                            part.SummonerName = botSelectedChamp.displayName + " bot";
                            control = RenderPlayer(selection, part);
                        }
                        else
                        {
                            control.PlayerName.Content = "Unknown Summoner";
                        }
                        //Display purple side if we have gone through our team
                        if (i > ChampDTO.TeamOne.Count)
                        {
                            i = 0;
                            PurpleSide = true;
                        }

                        if (!PurpleSide)
                        {
                            BlueListView.Items.Add(control);
                        }
                        else
                        {
                            PurpleListView.Items.Add(control);
                        }
                    }

                    //Do aram hack!
                    if (OtherPlayers.Count > 0)
                    {
                        if (AreWePurpleSide)
                        {
                            BlueListView.Items.Clear();
                        }
                        else
                        {
                            PurpleListView.Items.Clear();
                        }

                        foreach (PlayerChampionSelectionDTO hackSelection in OtherPlayers)
                        {
                            ChampSelectPlayer control = new ChampSelectPlayer();
                            PlayerParticipant player = new PlayerParticipant();
                            player.SummonerName = hackSelection.SummonerInternalName;
                            control = RenderPlayer(hackSelection, player);

                            if (AreWePurpleSide)
                            {
                                BlueListView.Items.Add(control);
                            }
                            else
                            {
                                PurpleListView.Items.Add(control);
                            }
                        }
                    }

                    #endregion Display players
                }));

                #endregion In Champion Select
            }
            else if (((MessageReceivedEventArgs)message).Body.GetType() == typeof(PlayerCredentialsDto))
            {
                #region Launching Game

                PlayerCredentialsDto dto = ((MessageReceivedEventArgs)message).Body as PlayerCredentialsDto;
                Client.CurrentGame = dto;

                if (!HasLaunchedGame)
                {
                    HasLaunchedGame = true;
                    Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                    {
                        if (CountdownTimer != null)
                        {
                            CountdownTimer.Stop();
                        }
                        Client.QuitCurrentGame();
                    }));
                    Client.LaunchGame();
                }

                #endregion Launching Game
            }
            else if (((MessageReceivedEventArgs)message).Body.GetType() == typeof(TradeContractDTO))
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    TradeContractDTO TradeDTO = ((MessageReceivedEventArgs)message).Body as TradeContractDTO;
                    if (TradeDTO.State == "PENDING")
                    {
                        PlayerTradeControl.Visibility = System.Windows.Visibility.Visible;
                        PlayerTradeControl.Tag = TradeDTO;
                        PlayerTradeControl.AcceptButton.Visibility = System.Windows.Visibility.Visible;
                        PlayerTradeControl.DeclineButton.Content = "Decline";

                        champions MyChampion = champions.GetChampion((int)TradeDTO.ResponderChampionId);
                        PlayerTradeControl.MyChampImage.Source = MyChampion.icon;
                        PlayerTradeControl.MyChampLabel.Content = MyChampion.displayName;
                        champions TheirChampion = champions.GetChampion((int)TradeDTO.RequesterChampionId);
                        PlayerTradeControl.TheirChampImage.Source = TheirChampion.icon;
                        PlayerTradeControl.TheirChampLabel.Content = TheirChampion.displayName;
                        PlayerTradeControl.RequestLabel.Content = string.Format("{0} wants to trade!", TradeDTO.RequesterInternalSummonerName);
                    }
                    else if (TradeDTO.State == "CANCELED" || TradeDTO.State == "DECLINED" || TradeDTO.State == "BUSY")
                    {
                        PlayerTradeControl.Visibility = System.Windows.Visibility.Hidden;
                        NotificationPopup pop = new NotificationPopup(ChatSubjects.INVITE_STATUS_CHANGED, 
                            string.Format("{0} has {1} this trade", TradeDTO.RequesterInternalSummonerName, TradeDTO.State));

                        if (TradeDTO.State == "BUSY")
                            pop.NotificationTextBox.Text = string.Format("{0} is currently busy", TradeDTO.RequesterInternalSummonerName);

                        pop.Height = 200;
                        pop.OkButton.Visibility = System.Windows.Visibility.Visible;
                        pop.HorizontalAlignment = HorizontalAlignment.Right;
                        pop.VerticalAlignment = VerticalAlignment.Bottom;
                        Client.NotificationGrid.Children.Add(pop);
                    }
                }));
            }
        }
        public async void InitializePop(GameDTO InitialDTO)
        {
            List<Participant> AllParticipants = InitialDTO.TeamOne;
            AllParticipants.AddRange(InitialDTO.TeamTwo);
            if (InitialDTO.TeamOne[0] is ObfuscatedParticipant)
            {
                ReverseString = true;
            }

            foreach (Participant p in AllParticipants)
            {
                QueuePopPlayer player = new QueuePopPlayer();
                player.Width = 300;
                player.Height = 100;
                if (p is PlayerParticipant)
                {
                    PlayerParticipant playerPart = (PlayerParticipant)p;
                    player.PlayerLabel.Content = playerPart.SummonerName;
                    player.RankLabel.Content = "";
                    Team1ListBox.Items.Add(player);
                }
                else
                {
                    player.PlayerLabel.Content = "Enemy";
                    player.RankLabel.Content = "";
                    Team2ListBox.Items.Add(player);
                }
            }

            int i = 0;
            foreach (Participant p in AllParticipants)
            {
                if (p is PlayerParticipant)
                {
                    QueuePopPlayer player = (QueuePopPlayer)Team1ListBox.Items[i];
                    PlayerParticipant playerPart = (PlayerParticipant)p;
                    SummonerLeaguesDTO playerLeagues = await RiotCalls.GetAllLeaguesForPlayer(playerPart.SummonerId);
                    foreach (LeagueListDTO x in playerLeagues.SummonerLeagues)
                    {
                        if (x.Queue == "RANKED_SOLO_5x5")
                        {
                            player.RankLabel.Content = x.Tier + " " + x.RequestorsRank;
                        }
                    }
                    //People can be ranked without having solo queue so don't put if statement checking List.Length
                    if (String.IsNullOrEmpty((string)player.RankLabel.Content))
                    {
                        player.RankLabel.Content = "Unranked";
                    }
                    i++;
                }
            }

            if (Client.AutoAcceptQueue)
            {
                await RiotCalls.AcceptPoppedGame(true);
            }
        }