private void ProcessMyListingsSellOrders(HtmlNode root, string currency, MyListings myListings)
        {
            var saleNodes = root.SelectNodes("//div[contains(@id,'mylisting_')]");

            if (saleNodes != null)
            {
                int tempIndex = 0;
                foreach (var item in saleNodes)
                {
                    this.GetPendingTransactionData(item, tempIndex, myListings, ETransactionType.Sale, currency, false);

                    tempIndex++;
                }
            }
        }
        private void ProcessMyListingsSellOrders(HtmlNode root, string currency, MyListings myListings)
        {
            var saleNodes = root.SelectNodes("//div[contains(@id,'mylisting_')]");

            if (saleNodes != null)
            {
                var tempIndex = 0;
                foreach (var item in saleNodes)
                {
                    try
                    {
                        this.GetPendingTransactionData(item, tempIndex, myListings, ETransactionType.Sale, currency);
                    }
                    catch (Exception e)
                    {
                        Logger.Log.Error(
                            $"Error on getting pending transaction data - {e.Message}. \nNode-{item?.InnerHtml}",
                            e);
                    }

                    tempIndex++;
                }
            }
        }
        // public Task<MyListings> MyListingsAsync()
        // {
        // var result = new Task<MyListings>(MyListings);
        // result.Start();
        // return result;
        // }

        // public List<HistoryItem> History(int count = 100, int start = 0)
        // {
        // count = count > 500 ? 500 : count;

        // var data = new Dictionary<string, string>
        // {
        // {"count", count.ToString()},
        // {"start", start.ToString()}
        // };

        // var resp = _steam.Request(Urls.Market + "/myhistory/render/", Method.GET, Urls.Market, data, true);
        // JMyHistory respDes;

        // try
        // {
        // respDes = JsonConvert.DeserializeObject<JMyHistory>(resp.Data.Content);
        // }
        // catch
        // {
        // throw new SteamException("Cannot load market history");
        // }

        // if (!respDes.Success)
        // throw new SteamException("Cannot load market history");

        // if (respDes.TotalCount == null || respDes.TotalCount == 0)
        // return new List<HistoryItem>();

        // var doc = new HtmlDocument();
        // doc.LoadHtml(respDes.Html);

        // var historyNodes =
        // doc.DocumentNode.SelectNodes(
        // "//div[contains(@id, 'history_row_') and @class='market_listing_row market_recent_listing_row']");

        // var hoversMatches = Regex.Matches(respDes.Hovers,
        // @"(?<=CreateItemHoverFromContainer\( g_rgAssets,)(.*?)(?=\))");

        // var hovers = hoversMatches.Cast<Match>()
        // .Select(s => s.Value.Split(',').Apply(a => a.Trim(' ', '\''))) - Apply function is unknown, the method is unnecessary so far
        // .Where(w => w[0].Contains("_name"))
        // .Select(s => new HistoryItemHover
        // {
        // AppId = int.Parse(s[1]),
        // ContextId = int.Parse(s[2]),
        // AssetId = long.Parse(s[3]),
        // HoverId = s[0].Replace("_name", "")
        // });

        // var assets = respDes.Assets.SelectMany(s => s.Value.SelectMany(c => c.Value.Select(m => m.Value)));

        // var hoverAssetCompare = hovers
        // .Select(s => new KeyValuePair<HistoryItemHover, JDescription>(s, assets.First(f => f.Id == s.AssetId)));

        // var history = historyNodes.Select(s =>
        // {
        // var actionTypeString =
        // s.SelectSingleNode("div[@class='market_listing_left_cell market_listing_gainorloss']")
        // .InnerText.Trim();

        // EMyHistoryActionType actionType;
        // switch (actionTypeString)
        // {
        // case "+":
        // actionType = EMyHistoryActionType.Buy;
        // break;
        // case "-":
        // actionType = EMyHistoryActionType.Sell;
        // break;
        // default:
        // actionType = EMyHistoryActionType.None;
        // break;
        // }

        // var priceString = s.SelectSingleNode("div[contains(@class, 'market_listing_their_price')]")
        // .InnerText.Trim()
        // .Split(' ')[0];

        // var dates =
        // s.SelectNodes("div[contains(@class, 'market_listing_listed_date')]")
        // .Select(x => x.InnerText.Trim()).ToArray();

        // var memberString = s.SelectSingleNode(".//div[@class='market_listing_whoactedwith_name_block']");
        // var member = memberString?.ChildNodes[2].InnerText.Trim() ?? s.SelectSingleNode("div[contains(@class, 'market_listing_whoactedwith')]").InnerText.Trim();

        // return new HistoryItem
        // {
        // Asset = hoverAssetCompare.FirstOrDefault(w => w.Key.HoverId == s.Id).Value,
        // Game = s.SelectSingleNode(".//span[contains(@class, 'market_listing_game_name')]").InnerText.Trim(),
        // Name = s.SelectSingleNode(".//span[contains(@class, 'market_listing_item_name')]").InnerText.Trim(),
        // ActionType = actionType,
        // Member = member,
        // PlaceDate = string.IsNullOrEmpty(dates[0]) ? (DateTime?)null : Convert.ToDateTime(dates[0]),
        // DealDate = string.IsNullOrEmpty(dates[1]) ? (DateTime?)null : Convert.ToDateTime(dates[1]),
        // Price =
        // string.IsNullOrEmpty(priceString)
        // ? (double?)null
        // : double.Parse(priceString, NumberStyles.Currency, new CultureInfo("en-US"))

        // };
        // }).Where(w => w.ActionType != EMyHistoryActionType.None).ToList();

        // return history;
        // }
        public MyListings MyListings(string currency = "5", int start = 0, int count = 100)
        {
            var myListings = new MyListings();

            var @params = new Dictionary <string, string> {
                { "start", $"{start}" }, { "count", $"{count}" }
            };
            var resp = this.steam.Request(
                Urls.Market + "/mylistings/",
                Method.GET,
                Urls.Market,
                @params,
                true,
                proxy: this.Proxy);

            JMyListings respDes;

            try
            {
                respDes = JsonConvert.DeserializeObject <JMyListings>(resp.Data.Content);
            }
            catch (Exception e)
            {
                throw new SteamException($"Cannot load market listings - {e.Message}");
            }

            if (!respDes.Success)
            {
                throw new SteamException("Cannot load market listings. Steam request failed.");
            }

            var totalCount = respDes.ActiveListingsCount;

            var html = respDes.ResultsHtml;
            var doc  = new HtmlDocument();

            doc.LoadHtml(html);
            var root = doc.DocumentNode;

            var ordersCountNode = root.SelectSingleNode(".//span[@id='my_market_buylistings_number']");

            if (ordersCountNode == null)
            {
                throw new SteamException("Cannot find buy listings node");
            }

            var ordersCountParse = int.TryParse(ordersCountNode.InnerText, out var ordersCount);

            if (!ordersCountParse)
            {
                throw new SteamException("Cannot parse buy listings node value");
            }

            var sellCountNode = root.SelectSingleNode(".//span[@id='my_market_selllistings_number']");

            if (sellCountNode == null)
            {
                throw new SteamException("Cannot find sell listings node");
            }

            var sellCountParse = int.TryParse(sellCountNode.InnerText, out var sellCount);

            if (!sellCountParse)
            {
                throw new SteamException("Cannot parse sell listings node value");
            }

            var confirmCountNode = root.SelectSingleNode(".//span[@id='my_market_listingstoconfirm_number']");
            var confirmCount     = 0;

            if (confirmCountNode != null)
            {
                var confirmCountParse = int.TryParse(confirmCountNode.InnerText, out confirmCount);
                if (!confirmCountParse)
                {
                    throw new SteamException("Cannot parse confirm listings node value");
                }
            }

            myListings.Total          = totalCount;
            myListings.ItemsToBuy     = ordersCount;
            myListings.ItemsToConfirm = confirmCount;
            myListings.ItemsToSell    = sellCount;

            var tempIndex   = 0;
            var ordersNodes = root.SelectNodes("//div[contains(@id,'mybuyorder_')]");

            if (ordersNodes != null)
            {
                foreach (var item in ordersNodes)
                {
                    try
                    {
                        this.GetPendingTransactionData(item, tempIndex, myListings, ETransactionType.Order, currency);
                    }
                    catch (Exception e)
                    {
                        Logger.Log.Error(
                            $"Error on getting pending transaction data - {e.Message}.{Environment.NewLine}Node-{item?.InnerHtml}",
                            e);
                    }

                    tempIndex++;
                }
            }

            if (myListings.Orders.Any())
            {
                myListings.SumOrderPricesToBuy = Math.Round(myListings.Orders.Sum(s => s.Price), 2);
            }

            this.ProcessMyListingsSellOrders(root, currency, myListings);

            return(myListings);
        }
        private void GetPendingTransactionData(
            HtmlNode item,
            int tempIndex,
            MyListings myListings,
            ETransactionType type,
            string currency)
        {
            if (item == null)
            {
                return;
            }

            var node = item.SelectSingleNode(".//span[@class='market_listing_price']");

            if (node == null)
            {
                throw new SteamException(
                          $"Cannot parse order listing price and quantity node. Item index [{tempIndex}]");
            }

            var date = Regex.Match(item.InnerText, @"Listed: (.+)?\s").Groups[1].Value.Trim();
            var game = item.SelectSingleNode("//span[@class='market_listing_game_name']")?.InnerText;

            if (type == ETransactionType.Order)
            {
                var priceAndQuantityString = node.InnerText.Replace("\r", string.Empty).Replace("\n", string.Empty)
                                             .Replace("\t", string.Empty).Replace(" ", string.Empty);
                var priceAndQuantitySplit = priceAndQuantityString.Split('@');

                double price;
                try
                {
                    var priceParse     = priceAndQuantitySplit[1].Replace(".", string.Empty);
                    var currencySymbol = SteamCurrencies.Currencies[currency];
                    double.TryParse(priceParse.Replace(currencySymbol, string.Empty), out price);
                }
                catch (Exception)
                {
                    throw new SteamException($"Cannot parse order listing price. Item index [{tempIndex}]");
                }

                var quantityParse = int.TryParse(priceAndQuantitySplit[0], out var quantity);

                if (!quantityParse)
                {
                    throw new SteamException($"Cannot parse order listing quantity. Item index [{tempIndex}]");
                }

                var orderIdMatch = Regex.Match(item.InnerHtml, "(?<=mbuyorder_)([0-9]*)(?=_name)");

                if (!orderIdMatch.Success)
                {
                    throw new SteamException($"Cannot find order listing ID. Item index [{tempIndex}]");
                }

                var orderIdParse = long.TryParse(orderIdMatch.Value, out var orderId);

                if (!orderIdParse)
                {
                    throw new SteamException($"Cannot parse order listing ID. Item index [{tempIndex}]");
                }

                var imageUrl = item.SelectSingleNode($"//img[contains(@id, 'mylisting_{orderId}_image')]")
                               .Attributes["src"].Value;

                imageUrl = Regex.Match(imageUrl, "image/(.*)/").Groups[1].Value;

                var urlNode = item.SelectSingleNode(".//a[@class='market_listing_item_name_link']");
                if (urlNode == null)
                {
                    throw new SteamException($"Cannot find order listing url. Item index [{tempIndex}]");
                }

                var url = urlNode.Attributes["href"].Value;

                var hashName = MarketUtils.HashNameFromUrl(url);
                var appId    = MarketUtils.AppIdFromUrl(url);

                var nameNode = urlNode.InnerText;

                myListings.Orders.Add(
                    new MyListingsOrdersItem
                {
                    AppId    = appId,
                    HashName = hashName,
                    Name     = nameNode,
                    Date     = date,
                    OrderId  = orderId,
                    Price    = price,
                    Quantity = quantity,
                    Url      = url,
                    ImageUrl = imageUrl,
                    Game     = game
                });
            }
            else
            {
                var priceString = node.InnerText.Replace("\r", string.Empty).Replace("\n", string.Empty)
                                  .Replace("\t", string.Empty).Replace(" ", string.Empty);
                double price;
                try
                {
                    var priceParse     = priceString.Split('(')[0];
                    var currencySymbol = SteamCurrencies.Currencies[currency];
                    double.TryParse(priceParse.Replace(currencySymbol, string.Empty), out price);
                }
                catch (Exception)
                {
                    throw new SteamException($"Cannot parse order listing price. Item index [{tempIndex}]");
                }

                var saleIdMatch = Regex.Match(item.InnerHtml, "(?<=mylisting_)([0-9]*)(?=_name)");
                if (!saleIdMatch.Success)
                {
                    throw new SteamException($"Cannot find sale listing ID. Item index [{tempIndex}]");
                }

                var saleIdParse = long.TryParse(saleIdMatch.Value, out var saleId);

                if (!saleIdParse)
                {
                    throw new SteamException($"Cannot parse sale listing ID. Item index [{tempIndex}]");
                }

                var imageUrl = item.SelectSingleNode($"//img[contains(@id, 'mylisting_{saleId}_image')]")
                               .Attributes["src"].Value.Replace("38fx38f", string.Empty).Replace(
                    "https://steamcommunity-a.akamaihd.net/economy/image/",
                    string.Empty);

                var urlNode = item.SelectSingleNode(".//a[@class='market_listing_item_name_link']");
                if (urlNode == null)
                {
                    throw new SteamException($"Cannot find sale listing url. Item index [{tempIndex}]");
                }

                var url = urlNode.Attributes["href"].Value;

                var hashName = MarketUtils.HashNameFromUrl(url);
                var appId    = MarketUtils.AppIdFromUrl(url);

                var nameNode = urlNode.InnerText;

                var result = new MyListingsSalesItem
                {
                    AppId    = appId,
                    HashName = hashName,
                    Name     = nameNode,
                    Date     = date,
                    SaleId   = saleId,
                    Price    = price,
                    Url      = url,
                    ImageUrl = imageUrl,
                    Game     = game
                };

                var isConfirmation = item.InnerHtml.Contains("CancelMarketListingConfirmation");

                if (isConfirmation == false)
                {
                    myListings.Sales.Add(result);
                }
                else
                {
                    myListings.ConfirmationSales.Add(result);
                }
            }
        }
 public void LoadMyListings()
 {
     this.myListings = CurrentSession.SteamManager.MarketClient.MyListings();
 }
        // public Task<MyListings> MyListingsAsync()
        // {
        // var result = new Task<MyListings>(MyListings);
        // result.Start();
        // return result;
        // }

        // public List<HistoryItem> History(int count = 100, int start = 0)
        // {
        // count = count > 500 ? 500 : count;

        // var data = new Dictionary<string, string>
        // {
        // {"count", count.ToString()},
        // {"start", start.ToString()}
        // };

        // var resp = _steam.Request(Urls.Market + "/myhistory/render/", Method.GET, Urls.Market, data, true);
        // JMyHistory respDes;

        // try
        // {
        // respDes = JsonConvert.DeserializeObject<JMyHistory>(resp.Data.Content);
        // }
        // catch
        // {
        // throw new SteamException("Cannot load market history");
        // }

        // if (!respDes.Success)
        // throw new SteamException("Cannot load market history");

        // if (respDes.TotalCount == null || respDes.TotalCount == 0)
        // return new List<HistoryItem>();

        // var doc = new HtmlDocument();
        // doc.LoadHtml(respDes.Html);

        // var historyNodes =
        // doc.DocumentNode.SelectNodes(
        // "//div[contains(@id, 'history_row_') and @class='market_listing_row market_recent_listing_row']");

        // var hoversMatches = Regex.Matches(respDes.Hovers,
        // @"(?<=CreateItemHoverFromContainer\( g_rgAssets,)(.*?)(?=\))");

        // var hovers = hoversMatches.Cast<Match>()
        // .Select(s => s.Value.Split(',').Apply(a => a.Trim(' ', '\''))) - Apply function is unknown, the method is unnecessary so far
        // .Where(w => w[0].Contains("_name"))
        // .Select(s => new HistoryItemHover
        // {
        // AppId = int.Parse(s[1]),
        // ContextId = int.Parse(s[2]),
        // AssetId = long.Parse(s[3]),
        // HoverId = s[0].Replace("_name", "")
        // });

        // var assets = respDes.Assets.SelectMany(s => s.Value.SelectMany(c => c.Value.Select(m => m.Value)));

        // var hoverAssetCompare = hovers
        // .Select(s => new KeyValuePair<HistoryItemHover, JDescription>(s, assets.First(f => f.Id == s.AssetId)));

        // var history = historyNodes.Select(s =>
        // {
        // var actionTypeString =
        // s.SelectSingleNode("div[@class='market_listing_left_cell market_listing_gainorloss']")
        // .InnerText.Trim();

        // EMyHistoryActionType actionType;
        // switch (actionTypeString)
        // {
        // case "+":
        // actionType = EMyHistoryActionType.Buy;
        // break;
        // case "-":
        // actionType = EMyHistoryActionType.Sell;
        // break;
        // default:
        // actionType = EMyHistoryActionType.None;
        // break;
        // }

        // var priceString = s.SelectSingleNode("div[contains(@class, 'market_listing_their_price')]")
        // .InnerText.Trim()
        // .Split(' ')[0];

        // var dates =
        // s.SelectNodes("div[contains(@class, 'market_listing_listed_date')]")
        // .Select(x => x.InnerText.Trim()).ToArray();

        // var memberString = s.SelectSingleNode(".//div[@class='market_listing_whoactedwith_name_block']");
        // var member = memberString?.ChildNodes[2].InnerText.Trim() ?? s.SelectSingleNode("div[contains(@class, 'market_listing_whoactedwith')]").InnerText.Trim();

        // return new HistoryItem
        // {
        // Asset = hoverAssetCompare.FirstOrDefault(w => w.Key.HoverId == s.Id).Value,
        // Game = s.SelectSingleNode(".//span[contains(@class, 'market_listing_game_name')]").InnerText.Trim(),
        // Name = s.SelectSingleNode(".//span[contains(@class, 'market_listing_item_name')]").InnerText.Trim(),
        // ActionType = actionType,
        // Member = member,
        // PlaceDate = string.IsNullOrEmpty(dates[0]) ? (DateTime?)null : Convert.ToDateTime(dates[0]),
        // DealDate = string.IsNullOrEmpty(dates[1]) ? (DateTime?)null : Convert.ToDateTime(dates[1]),
        // Price =
        // string.IsNullOrEmpty(priceString)
        // ? (double?)null
        // : double.Parse(priceString, NumberStyles.Currency, new CultureInfo("en-US"))

        // };
        // }).Where(w => w.ActionType != EMyHistoryActionType.None).ToList();

        // return history;
        // }
        public MyListings MyListings(string currency = "5", int count = 100)
        {
            var myListings = new MyListings
            {
                Orders            = new List <MyListingsOrdersItem>(),
                Sales             = new List <MyListingsSalesItem>(),
                ConfirmationSales = new List <MyListingsSalesItem>()
            };

            var start   = 0;
            var @params = new Dictionary <string, string> {
                { "start", $"{start}" }, { "count", $"{count}" }
            };
            var resp = this.steam.Request(Urls.Market + "/mylistings/", Method.GET, Urls.Market, @params, true);

            JMyListings respDes;

            try
            {
                respDes = JsonConvert.DeserializeObject <JMyListings>(resp.Data.Content);
            }catch (Exception e)
            {
                throw new SteamException($"Cannot load market listings - {e.Message}");
            }

            if (!respDes.Success)
            {
                throw new SteamException("Cannot load market listings");
            }

            var totalCount = respDes.ActiveListingsCount;

            Program.LoadingForm.SetTotalItemsCount(
                totalCount,
                (int)Math.Ceiling((double)totalCount / count),
                "Total listings count");

            var html = respDes.ResultsHtml;
            var doc  = new HtmlDocument();

            doc.LoadHtml(html);
            var root = doc.DocumentNode;

            var ordersCountNode = root.SelectSingleNode(".//span[@id='my_market_buylistings_number']");

            if (ordersCountNode == null)
            {
                throw new SteamException("Cannot find buy listings node");
            }

            var ordersCountParse = int.TryParse(ordersCountNode.InnerText, out var ordersCount);

            if (!ordersCountParse)
            {
                throw new SteamException("Cannot parse buy listings node value");
            }

            var sellCountNode = root.SelectSingleNode(".//span[@id='my_market_selllistings_number']");

            if (sellCountNode == null)
            {
                throw new SteamException("Cannot find sell listings node");
            }

            var sellCountParse = int.TryParse(sellCountNode.InnerText, out var sellCount);

            if (!sellCountParse)
            {
                throw new SteamException("Cannot parse sell listings node value");
            }

            var confirmCountNode = root.SelectSingleNode(".//span[@id='my_market_listingstoconfirm_number']");
            var confirmCount     = 0;

            if (confirmCountNode != null)
            {
                var confirmCountParse = int.TryParse(confirmCountNode.InnerText, out confirmCount);
                if (!confirmCountParse)
                {
                    throw new SteamException("Cannot parse confirm listings node value");
                }
            }

            myListings.ItemsToBuy     = ordersCount;
            myListings.ItemsToConfirm = confirmCount;
            myListings.ItemsToSell    = sellCount;

            var tempIndex   = 0;
            var ordersNodes = root.SelectNodes("//div[contains(@id,'mybuyorder_')]");

            if (ordersNodes != null)
            {
                foreach (var item in ordersNodes)
                {
                    this.GetPendingTransactionData(item, tempIndex, myListings, ETransactionType.Order, currency, true);

                    tempIndex++;
                }

                myListings.SumOrderPricesToBuy = Math.Round(myListings.Orders.Sum(s => s.Price), 2);
            }

            this.ProcessMyListingsSellOrders(root, currency, myListings);

            while (start < totalCount)
            {
                @params = new Dictionary <string, string> {
                    { "start", $"{start}" }, { "count", $"{count}" }
                };
                resp    = this.steam.Request(Urls.Market + "/mylistings/", Method.GET, Urls.Market, @params, true);
                respDes = JsonConvert.DeserializeObject <JMyListings>(resp.Data.Content);
                html    = respDes.ResultsHtml;
                doc.LoadHtml(html);
                root = doc.DocumentNode;

                this.ProcessMyListingsSellOrders(root, currency, myListings);
                start += count;

                Program.LoadingForm.TrackLoadedIteration("Page {currentPage} of {totalPages} loaded");
            }

            return(myListings);
        }