aboutsummaryrefslogtreecommitdiff
path: root/Source/Assistant/SkuAssist.cs
blob: 121bc88aa5747e15cea2f1890e0ee53a189b5678 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace Rehau.Sku.Assist
{
    public enum ResponseOrder
    {
        NoSettings,
        Relevance,
        Name,
        Price,
        Series
    }

    static class SkuAssist
    {
        public static async Task<IProduct> GetProduct(string request)
        {
            Uri uri = request.ConvertToUri(ResponseOrder.NoSettings);

            Task<string> contentTask = Task.Run(() => HttpClientUtil.GetContentByUriAsync(uri));
            Task<IDocument> documentTask = await contentTask.ContinueWith(content => HttpClientUtil.ContentToDocAsync(content));

            IProduct product = await documentTask.ContinueWith(doc => SkuAssist.GetFirstProduct(doc.Result));
            return product;
        }

        public static IProduct GetFirstProduct(IDocument doc)
        {
            return doc
                .All
                .Where(e => e.ClassName == "product-item__desc-top")
                .Where(e => Regex.IsMatch(e.Children[0].TextContent, @"\d{11}", RegexOptions.None))
                .Select(e => 
                    new Product(e.Children[0].TextContent,
                    e.Children[1].TextContent.Trim(new[] { '\n', ' ' })))
                .FirstOrDefault();
        }

        public static Uri GetFirstResultLink(IDocument doc)
        {
            var link = new Uri(doc
                .Links
                .Where(e => e.ClassName == "product-item__title-link js-name")
                .Select(l => ((IHtmlAnchorElement)l).Href)
                .FirstOrDefault());
            return link;
        }

        public static string GetFistResultImageLink(IDocument doc)
        {
            var imageSource = doc.Images
                .Where(x => x.ClassName == "product-item__image")
                .FirstOrDefault();
            return imageSource != null ? imageSource.Source : "Нет ссылки";
        }
    }
}