public ScanResultItem ParseResultWindowRareItem(string fileName, ScanInfo scanInfo, AndroidConnector android)
        {
            ScanResultItem exchangeInfo = new ScanResultItem()
            {
                Found    = true,
                ScanInfo = scanInfo
            };

            using (var image = Image.Load <Rgba32>(fileName))
            {
                image.Clone(ctx => ctx.Crop(new Rectangle(996, 159, 549, 66))).Save($"itemname.png");
                string itemName = GetTextFromImage("itemname.png");
                if (
                    (!scanInfo.RealName.Contains("★") && itemName.ToLower() != scanInfo.RealName.ToLower()) ||
                    (scanInfo.RealName.Contains("★") && !itemName.Contains("*") &&
                     itemName.ToLower() != "andrei card" &&
                     itemName.ToLower() != "zipper beartcard" &&
                     itemName.ToLower() != "archer skeletontcard"
                    )
                    )
                {
                    if (scanInfo.RealName.Contains("★"))
                    {
                        Console.WriteLine("Star card not found");
                    }
                    scanInfo.Message = "Something is wrong, names do NOT match";
                    return(ScanResult.BuildError <ScanResultItem>(scanInfo));
                }


                exchangeInfo.Price = int.Parse(GetPrice(image), CultureInfo.InvariantCulture);

                string amount = GetAmount(image);
                if (amount == "")
                {
                    scanInfo.Message = "Could not find the right amount";
                    return(ScanResult.BuildError <ScanResultItem>(scanInfo));
                }
                exchangeInfo.Amount   = int.Parse(amount, CultureInfo.InvariantCulture);
                exchangeInfo.SnapTime = GetSnapTime(image);


                exchangeInfo.Found = true;
            }
            return(exchangeInfo);
        }
        private async static void RunScanner()
        {
            //status.SetStatus("Starting up", "Checking if in exchange");
            //if (!await scanner.IsExchangeOpen(androidConnection))
            //{
            //    status.SetStatus("Restarting RO", "");
            //    await scanner.RestartRo(androidConnection);
            //    status.SetStatus("Opening Exchange", "");
            //    await scanner.OpenExchange(androidConnection, 0);
            //}
            //status.SetStatus("Starting up", "Started up");


            int errorCount      = 0;
            int majorErrorcount = 0;

            /* {
             *   ScanInfo scanInfo = new ScanInfo()
             *   {
             *       RealName = "Eye of Dullahan",
             *       SearchName = "Eye of Dullahan",
             *       SearchIndex = -1,
             *       Override = false
             *   };
             *
             *   List<ScanResultEquip> exchangeInfo = await scanner.ScanEquip(androidConnection, scanInfo);
             * }*/


            using (HttpClient client = new HttpClient())
            {
                while (true)
                {
                    CancelScan = false;

                    if (Restart)
                    {
                        CurrentStatus = Status.Restarting;
                        status.SetStatus("Restarting RO", "");
                        await scanner.RestartRo(androidConnection);

                        status.SetStatus("Opening Exchange", "");
                        await scanner.OpenExchange(androidConnection, 0);

                        Restart       = false;
                        CurrentStatus = Status.Idle;
                    }


                    if (CurrentStatus == Status.Idle)
                    {
                        status.SetStatus("Idle", "");
                        await Task.Delay(1000);

                        continue;
                    }

                    Program.status.SetStatus("Finding new item to scan", "");
                    HttpRequestMessage request;
                    if (CurrentStatus == Status.Equip)
                    {
                        request = new HttpRequestMessage(HttpMethod.Get, $"{ApiEndPoint}/api/scanner/nextscanequip");
                    }
                    else if (CurrentStatus == Status.Rare)
                    {
                        request = new HttpRequestMessage(HttpMethod.Get, $"{ApiEndPoint}/api/scanner/nextscanitem");
                    }
                    else
                    {
                        continue;
                    }
                    request.Headers.Add("Accept", "application/json");
                    request.Headers.Add("User-Agent", "BorfRoScanner");
                    var response = client.SendAsync(request).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        using var responseStream = await response.Content.ReadAsStreamAsync();

                        var options = new JsonSerializerOptions
                        {
                            IgnoreNullValues = true
                        };
                        var data = await JsonSerializer.DeserializeAsync <NextScanItemResponse>(responseStream, options);

                        Program.status.SetStatus("Scanning item", "");
                        Program.status.SetItem(data.name);

                        ScanInfo scanInfo = new ScanInfo()
                        {
                            RealName    = data.name,
                            SearchName  = data.scanname,
                            SearchIndex = data.scanindex,
                            Override    = data.@override
                        };
                        if (data.scanname == "")
                        {
                            scanInfo.SearchName = data.name;
                            if (scanInfo.SearchName.Contains("["))
                            {
                                scanInfo.SearchName = scanInfo.SearchName.Substring(0, scanInfo.SearchName.IndexOf("["));
                            }
                        }

                        if (data.type.ToLower().StartsWith("equipment"))
                        {
                            Stopwatch sw = new Stopwatch();
                            sw.Start();
                            List <ScanResultEquip> exchangeInfo = await scanner.ScanEquip(androidConnection, scanInfo);

                            sw.Stop();
                            log.Log(scanInfo.RealName, $"Found Item in {sw.Elapsed.TotalSeconds} seconds\n{exchangeInfo}\n");
                            bool error = exchangeInfo.Any(e => e.Error);
                            status.SetStatus("Done Scanning", "Posting results");
                            request = new HttpRequestMessage(HttpMethod.Post, $"{ApiEndPoint}/api/scanner/result");
                            request.Headers.Add("Accept", "application/json");
                            request.Headers.Add("User-Agent", "BorfRoScanner");
                            request.Content = new StringContent(JsonSerializer.Serialize(new
                            {
                                data.id,
                                error    = error,
                                results  = exchangeInfo,
                                clientId = hostname
                            }), Encoding.UTF8, "application/json");
                            try
                            {
                                response = await client.SendAsync(request);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                            }
                        }
                        else
                        {
                            Stopwatch sw = new Stopwatch();
                            sw.Start();
                            ScanResultItem exchangeInfo = await scanner.ScanRareItem(androidConnection, scanInfo);

                            sw.Stop();
                            log.Log(scanInfo.RealName, $"Found Item in {sw.Elapsed.TotalSeconds} seconds\n{exchangeInfo}\n");
                            request = new HttpRequestMessage(HttpMethod.Post, $"{ApiEndPoint}/api/scanner/result");
                            request.Headers.Add("Accept", "application/json");
                            request.Headers.Add("User-Agent", "BorfRoScanner");
                            request.Content = new StringContent(JsonSerializer.Serialize(new
                            {
                                data.id,
                                price     = exchangeInfo.Price,
                                amount    = exchangeInfo.Amount,
                                error     = exchangeInfo.Error,
                                errormsg  = exchangeInfo.ScanInfo.Message,
                                snapping  = exchangeInfo.Snapping,
                                snapTime  = exchangeInfo.SnapTime,
                                ScanIndex = exchangeInfo.ScanInfo.SearchIndex
                            }), Encoding.UTF8, "application/json");

                            response = await client.SendAsync(request);

                            if (exchangeInfo.Error)
                            {
                                errorCount++;
                                Console.WriteLine("Error scanning card!");
                                Console.WriteLine(exchangeInfo.ScanInfo.Message);
                            }
                            else
                            {
                                errorCount      = 0;
                                majorErrorcount = 0;
                            }
                        }
                    }


                    if (errorCount > 10)
                    {
                        Console.WriteLine("Got over 10 errors, increasing major errors...");
                        if (majorErrorcount > 2)
                        {
                            CurrentStatus = Status.Idle;
                        }
                        else
                        {
                            Restart = true;
                            Console.WriteLine("Too many errors, restarting game");
                            majorErrorcount++;
                            errorCount = 0;
                        }
                    }
                }
            }
        }
        public async Task <ScanResultItem> ScanRareItem(AndroidConnector android, ScanInfo scanInfo)
        {
            Console.WriteLine("- Opening search window");
            await CloseSearch(android);
            await ClickSearchButton(android);
            await ClickSearchBox(android);

            string itemName = scanInfo.SearchName;

            if (itemName.Contains("★"))
            {
                itemName = itemName.Substring(0, itemName.IndexOf("★")).Trim();
            }

            await android.Text(itemName);

            await ClickSearchWindowSearchButton(android); //to close text input
            await ClickSearchWindowSearchButton(android);

            Console.WriteLine("- Scanning search result");
            await android.Screenshot("searchresult.png");

            List <int> indices = FindSearchResult("searchresult.png", scanInfo);

            if (indices.Count == 0)
            {
                //TODO: do something with item0.png - item9.png
                Console.WriteLine("- Error, could not find item");
                await CloseSearch(android);

                return(ScanResult.BuildError <ScanResultItem>(scanInfo));
            }
            if (indices[0] != scanInfo.SearchIndex)
            {
                if (scanInfo.SearchIndex != -1)
                {
                    Console.WriteLine("- Warning, search index not correct");
                }
                scanInfo.SearchIndex = indices[0];
            }


            for (int i = 0; i < indices.Count; i++)
            {
                await ClickSearchWindowIndex(android, indices[i]);

                await Task.Delay(1500); // the UI needs some time to load the card

                Console.WriteLine("- Checking if any items are on sale");
                await android.Screenshot("shopitems.png");

                using (var image = Image.Load <Rgba32>("shopitems.png"))
                    image.Clone(ctx => ctx.Crop(new Rectangle(975, 505, 368, 64))).Save($"nosale.png");


                bool nosale = false;
                if (GetTextFromImage("nosale.png").ToLower().Contains("currently"))
                {
                    nosale = true;
                    Console.WriteLine("- No items currently on sale");
                    if (i + 1 >= indices.Count)
                    {
                        return new ScanResultItem()
                               {
                                   Found    = false,
                                   ScanInfo = scanInfo
                               }
                    }
                    ;
                }

                if (!nosale)
                {
                    await ClickShopItem(android, 0); // these items should only give 1 item result
                    await ClickShopBuyButton(android);

                    await Task.Delay(1500); // the UI needs some time to load the card

                    Console.WriteLine("- Scanning item");
                    await android.Screenshot("shopresult.png");
                    await ClickShopCloseItem(android);

                    ScanResultItem priceInfo = ParseResultWindowRareItem("shopresult.png", scanInfo, android);
                    if (!priceInfo.Error || i + 1 >= indices.Count)
                    {
                        priceInfo.Error = false;

                        return(priceInfo);
                    }
                }
                scanInfo.Message = "";
                Console.WriteLine("Item does not match, or not found on exchange with multiple items, trying to rescan it");
                await CloseSearch(android);
                await ClickSearchButton(android);
                await ClickSearchBox(android);

                await android.Text(itemName);
                await ClickSearchWindowSearchButton(android); //to close text input
                await ClickSearchWindowSearchButton(android);
            }

            return(null);
        }
    }