Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MWMPlacePageData.mm « PlacePage « UI « Maps « iphone - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c93aa37519e29062c6aeca144bf814ee7b59443f (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
#import "MWMPlacePageData.h"
#import "AppInfo.h"
#import "LocaleTranslator.h"
#import "MWMBannerHelpers.h"
#import "MWMNetworkPolicy.h"
#import "MWMUGCViewModel.h"
#import "SwiftBridge.h"

#include "Framework.h"

#include "local_ads/event.hpp"

#include "platform/preferred_languages.hpp"

#include "partners_api/booking_api.hpp"

#include "3party/opening_hours/opening_hours.hpp"

using namespace place_page;

namespace
{
NSString * const kUserDefaultsLatLonAsDMSKey = @"UserDefaultsLatLonAsDMS";
}  // namespace

@interface MWMPlacePageData ()

@property(copy, nonatomic) NSString * cachedMinPrice;
@property(nonatomic) id<MWMBanner> nativeAd;
@property(copy, nonatomic) NSArray<MWMGalleryItemModel *> * photos;
@property(copy, nonatomic) NSArray<MWMViatorItemModel *> * viatorItems;
@property(nonatomic) NSNumberFormatter * currencyFormatter;
@property(nonatomic, readwrite) MWMUGCViewModel * ugc;

@end

@implementation MWMPlacePageData
{
  Info m_info;

  std::vector<Sections> m_sections;
  std::vector<PreviewRows> m_previewRows;
  std::vector<SpecialProject> m_specialProjectRows;
  std::vector<MetainfoRows> m_metainfoRows;
  std::vector<AdRows> m_adRows;
  std::vector<ButtonsRows> m_buttonsRows;
  std::vector<HotelPhotosRow> m_hotelPhotosRows;
  std::vector<HotelDescriptionRow> m_hotelDescriptionRows;
  std::vector<HotelFacilitiesRow> m_hotelFacilitiesRows;
  std::vector<HotelReviewsRow> m_hotelReviewsRows;

  booking::HotelInfo m_hotelInfo;

  uint64_t m_cianRequestId;
}

- (instancetype)initWithPlacePageInfo:(Info const &)info
{
  self = [super init];
  if (self)
    m_info = info;

  return self;
}

#pragma mark - Filling sections

- (void)fillSections
{
  m_sections.clear();
  m_previewRows.clear();
  m_metainfoRows.clear();
  m_adRows.clear();
  m_buttonsRows.clear();
  m_hotelPhotosRows.clear();
  m_hotelDescriptionRows.clear();
  m_hotelReviewsRows.clear();
  m_hotelFacilitiesRows.clear();

  m_sections.push_back(Sections::Preview);
  [self fillPreviewSection];

  // It's bookmark.
  if (m_info.IsBookmark())
    m_sections.push_back(Sections::Bookmark);

  // There is always at least coordinate meta field.
  m_sections.push_back(Sections::Metainfo);
  [self fillMetaInfoSection];

  auto const & taxiProviders = [self taxiProviders];
  if (!taxiProviders.empty())
  {
    m_sections.push_back(Sections::Ad);
    m_adRows.push_back(AdRows::Taxi);

    NSString * provider = nil;
    switch (taxiProviders.front())
    {
    case taxi::Provider::Uber: provider = kStatUber; break;
    case taxi::Provider::Yandex: provider = kStatYandex; break;
    }
    [Statistics logEvent:kStatPlacepageTaxiShow withParameters:@{ @"provider" : provider }];
  }

  if (m_info.ShouldShowAddPlace() || m_info.ShouldShowEditPlace() ||
      m_info.ShouldShowAddBusiness() || m_info.IsSponsored())
  {
    m_sections.push_back(Sections::Buttons);
    [self fillButtonsSection];
  }

  if (m_info.ShouldShowUGC())
    [self addUGCSections];
}

- (void)addUGCSections
{
  NSAssert(m_info.ShouldShowUGC(), @"");

  __weak auto wself = self;
  GetFramework().GetUGC(
      m_info.GetID(), [wself](ugc::UGC const & ugc, ugc::UGCUpdate const & update) {
        __strong auto self = wself;
        self.ugc = [[MWMUGCViewModel alloc] initWithUGC:ugc update:update];

        {
          auto & previewRows = self->m_previewRows;
          auto it = find(previewRows.begin(), previewRows.end(), PreviewRows::Address);
          if (it == previewRows.end())
            it = find(previewRows.begin(), previewRows.end(), PreviewRows::Space);

          previewRows.insert(it, PreviewRows::Review);
          self.refreshPreviewCallback();
        }

        auto & sections = self->m_sections;
        auto const begin = sections.begin();
        auto const end = sections.end();

        auto it = find(begin, end, Sections::Buttons);
        NSUInteger const position = std::distance(begin, it);
        NSUInteger length = 0;

        if (!self.ugc.isUGCEmpty)
        {
          length = 2;
          it = sections.insert(it, Sections::UGCRating) + 1;
          if (self.ugc.isUGCUpdateEmpty)
          {
            it = sections.insert(it, Sections::UGCAddReview) + 1;
            length++;
          }

          it = sections.insert(it, Sections::UGCReviews) + 1;
        }
        else if (self.ugc.isUGCUpdateEmpty)
        {
          it = sections.insert(it, Sections::UGCAddReview);
          length = 1;
        }
        else
        {
          it = sections.insert(it, Sections::UGCReviews);
          length = 1;
        }

        self.sectionsAreReadyCallback({position, length}, self, YES /* It's a section */);
      });
}

- (void)fillPreviewSection
{
  if (self.title.length) m_previewRows.push_back(PreviewRows::Title);
  if (self.externalTitle.length) m_previewRows.push_back(PreviewRows::ExternalTitle);
  if (self.subtitle.length || self.isMyPosition) m_previewRows.push_back(PreviewRows::Subtitle);
  if (self.schedule != OpeningHours::Unknown) m_previewRows.push_back(PreviewRows::Schedule);
  if (self.isBooking)
    m_previewRows.push_back(PreviewRows::Review);
  if (self.address.length) m_previewRows.push_back(PreviewRows::Address);
  m_previewRows.push_back(PreviewRows::Space);

  NSAssert(!m_previewRows.empty(), @"Preview row's can't be empty!");

  if (network_policy::CanUseNetwork() && ![MWMSettings adForbidden] && m_info.HasBanner() &&
      ![self isViator] && ![self isCian])
  {
    __weak auto wSelf = self;
    [[MWMBannersCache cache]
        getWithCoreBanners:banner_helpers::MatchPriorityBanners(m_info.GetBanners())
                 cacheOnly:NO
                   loadNew:YES
                completion:^(id<MWMBanner> ad, BOOL isAsync) {
                  __strong auto self = wSelf;
                  if (!self)
                    return;

                  self.nativeAd = ad;
                  self->m_previewRows.push_back(PreviewRows::Banner);
                  if (isAsync)
                    self.bannerIsReadyCallback();
                }];
  }
}

- (void)fillMetaInfoSection
{
  using namespace osm;
  auto const availableProperties = m_info.AvailableProperties();
  // We can't match each metadata property to its UI field and thats why we need to use our own
  // enum.
  for (auto const p : availableProperties)
  {
    switch (p)
    {
    case Props::OpeningHours: m_metainfoRows.push_back(MetainfoRows::OpeningHours); break;
    case Props::Phone: m_metainfoRows.push_back(MetainfoRows::Phone); break;
    case Props::Website:
      if (!self.isBooking)
        m_metainfoRows.push_back(MetainfoRows::Website);
      break;
    case Props::Email: m_metainfoRows.push_back(MetainfoRows::Email); break;
    case Props::Cuisine: m_metainfoRows.push_back(MetainfoRows::Cuisine); break;
    case Props::Operator: m_metainfoRows.push_back(MetainfoRows::Operator); break;
    case Props::Internet: m_metainfoRows.push_back(MetainfoRows::Internet); break;

    case Props::Wikipedia:
    case Props::Elevation:
    case Props::Stars:
    case Props::Flats:
    case Props::BuildingLevels:
    case Props::Level:
    case Props::Fax: break;
    }
  }

  auto const address = m_info.GetAddress();
  if (!address.empty())
    m_metainfoRows.push_back(MetainfoRows::Address);

  m_metainfoRows.push_back(MetainfoRows::Coordinate);

  switch (m_info.GetLocalAdsStatus())
  {
  case place_page::LocalAdsStatus::NotAvailable: break;
  case place_page::LocalAdsStatus::Candidate:
    m_metainfoRows.push_back(MetainfoRows::LocalAdsCandidate);
    break;
  case place_page::LocalAdsStatus::Customer:
    m_metainfoRows.push_back(MetainfoRows::LocalAdsCustomer);
    [self logLocalAdsEvent:local_ads::EventType::OpenInfo];
    break;
  }
}

- (void)fillButtonsSection
{
  // We don't have to show edit, add place or business if it's booking object.
  if (self.isBooking)
  {
    m_buttonsRows.push_back(ButtonsRows::HotelDescription);
    return;
  }

  if (m_info.ShouldShowAddPlace())
    m_buttonsRows.push_back(ButtonsRows::AddPlace);

  if (m_info.ShouldShowEditPlace())
    m_buttonsRows.push_back(ButtonsRows::EditPlace);

  if (m_info.ShouldShowAddBusiness())
    m_buttonsRows.push_back(ButtonsRows::AddBusiness);
}

- (void)insertSpecialProjectsSectionWithProject:(SpecialProject)project
{
  auto const begin = m_sections.begin();
  auto const end = m_sections.end();

  if (std::find(begin, end, Sections::SpecialProjects) != end)
    return;

  m_sections.insert(find(begin, end, Sections::Preview) + 1, Sections::SpecialProjects);
  m_specialProjectRows.emplace_back(project);

  self.sectionsAreReadyCallback({1, 1}, self, YES);
}

- (void)fillOnlineViatorSection
{
  if (!self.isViator)
    return;

  if (Platform::ConnectionStatus() == Platform::EConnectionType::CONNECTION_NONE)
    return;

  network_policy::CallPartnersApi([self](platform::NetworkPolicy const & canUseNetwork) {
    auto api = GetFramework().GetViatorApi(canUseNetwork);
    if (!api)
      return;

    std::string const currency = self.currencyFormatter.currencyCode.UTF8String;
    std::string const viatorId = [self sponsoredId].UTF8String;

    __weak auto wSelf = self;
    api->GetTop5Products(
        viatorId, currency, [wSelf, viatorId](std::string const & destId,
                                              std::vector<viator::Product> const & products) {
          __strong auto self = wSelf;
          if (!self || viatorId != destId)
            return;
          NSMutableArray<MWMViatorItemModel *> * items = [@[] mutableCopy];
          for (auto const & p : products)
          {
            auto imageURL = [NSURL URLWithString:@(p.m_photoUrl.c_str())];
            auto pageURL = [NSURL URLWithString:@(p.m_pageUrl.c_str())];
            if (!imageURL || !pageURL)
              continue;
            auto item = [[MWMViatorItemModel alloc] initWithImageURL:imageURL
                                                             pageURL:pageURL
                                                               title:@(p.m_title.c_str())
                                                              rating:p.m_rating
                                                            duration:@(p.m_duration.c_str())
                                                               price:@(p.m_priceFormatted.c_str())];
            [items addObject:item];
          }

          dispatch_async(dispatch_get_main_queue(), [items, self] {
            self.viatorItems = items;

            [self insertSpecialProjectsSectionWithProject:SpecialProject::Viator];
          });
        });
  });
}

- (void)fillOnlineCianSection
{
  if (![self isCian])
    return;

  [self insertSpecialProjectsSectionWithProject:SpecialProject::Cian];

  if (Platform::ConnectionStatus() == Platform::EConnectionType::CONNECTION_NONE)
  {
    self.cianIsReadyCallback(@[]);
    return;
  }

  network_policy::CallPartnersApi([self](platform::NetworkPolicy const & canUseNetwork) {
    auto api = GetFramework().GetCianApi(canUseNetwork);
    if (!api)
    {
      self.cianIsReadyCallback(@[]);
      return;
    }
    auto const latLon = [self latLon];

    __weak auto wSuccessSelf = self;
    __weak auto wErrorSelf = self;
    m_cianRequestId = api->GetRentNearby(
        latLon,
        [wSuccessSelf](std::vector<cian::RentPlace> const & places, uint64_t const requestId) {
          __strong auto self = wSuccessSelf;
          if (!self || self->m_cianRequestId != requestId)
            return;
          NSMutableArray<MWMCianItemModel *> * items = [@[] mutableCopy];
          for (auto const & p : places)
          {
            auto const & offers = p.m_offers;
            NSCAssert(!offers.empty(), @"Cian misses offers for place.");
            if (offers.empty())
              continue;
            auto const & firstOffer = offers.front();

            auto pageURL = [NSURL URLWithString:@(firstOffer.m_url.c_str())];
            if (!pageURL)
              continue;
            auto item =
                [[MWMCianItemModel alloc] initWithRoomsCount:firstOffer.m_roomsCount
                                                    priceRur:firstOffer.m_priceRur
                                                     pageURL:pageURL
                                                     address:@(firstOffer.m_address.c_str())];
            [items addObject:item];
          }

          dispatch_async(dispatch_get_main_queue(),
                         [self, items] { self.cianIsReadyCallback(items); });
        },
        [wErrorSelf](int code, uint64_t const requestId) {
          __strong auto self = wErrorSelf;
          if (!self || self->m_cianRequestId != requestId)
            return;
          dispatch_async(dispatch_get_main_queue(), [self] { self.cianIsReadyCallback(@[]); });
        });
  });
}

- (float)ratingRawValue
{
  return m_info.GetRatingRawValue();
}

- (void)fillOnlineBookingSections
{
  if (!self.isBooking)
    return;

  if (Platform::ConnectionStatus() == Platform::EConnectionType::CONNECTION_NONE)
    return;

  network_policy::CallPartnersApi([self](platform::NetworkPolicy const & canUseNetwork) {
    auto api = GetFramework().GetBookingApi(canUseNetwork);
    if (!api)
      return;

    std::string const hotelId = self.sponsoredId.UTF8String;
    __weak auto wSelf = self;
    api->GetHotelInfo(
        hotelId, [[AppInfo sharedInfo] twoLetterLanguageId].UTF8String,
        [wSelf, hotelId](booking::HotelInfo const & hotelInfo) {
          __strong auto self = wSelf;
          if (!self || hotelId != hotelInfo.m_hotelId)
            return;

          dispatch_async(dispatch_get_main_queue(), [self, hotelInfo] {
            m_hotelInfo = hotelInfo;

            auto & sections = self->m_sections;
            auto const begin = sections.begin();
            auto const end = sections.end();

            NSUInteger const position = find(begin, end, Sections::Bookmark) != end ? 2 : 1;
            NSUInteger length = 0;
            auto it = m_sections.begin() + position;

            if (!hotelInfo.m_photos.empty())
            {
              it = sections.insert(it, Sections::HotelPhotos) + 1;
              m_hotelPhotosRows.emplace_back(HotelPhotosRow::Regular);
              length++;
            }

            if (!hotelInfo.m_description.empty())
            {
              it = sections.insert(it, Sections::HotelDescription) + 1;
              m_hotelDescriptionRows.emplace_back(HotelDescriptionRow::Regular);
              m_hotelDescriptionRows.emplace_back(HotelDescriptionRow::ShowMore);
              length++;
            }

            auto const & facilities = hotelInfo.m_facilities;
            if (!facilities.empty())
            {
              it = sections.insert(it, Sections::HotelFacilities) + 1;
              auto & facilitiesRows = self->m_hotelFacilitiesRows;
              auto const size = facilities.size();
              auto constexpr maxNumberOfHotelCellsInPlacePage = 3UL;

              if (size > maxNumberOfHotelCellsInPlacePage)
              {
                facilitiesRows.insert(facilitiesRows.begin(), maxNumberOfHotelCellsInPlacePage,
                                      HotelFacilitiesRow::Regular);
                facilitiesRows.emplace_back(HotelFacilitiesRow::ShowMore);
              }
              else
              {
                facilitiesRows.insert(facilitiesRows.begin(), size, HotelFacilitiesRow::Regular);
              }

              length++;
            }

            auto const & reviews = hotelInfo.m_reviews;
            if (!reviews.empty())
            {
              sections.insert(it, Sections::HotelReviews);
              auto const size = reviews.size();
              auto & reviewsRows = self->m_hotelReviewsRows;

              reviewsRows.emplace_back(HotelReviewsRow::Header);
              reviewsRows.insert(reviewsRows.end(), size, HotelReviewsRow::Regular);
              reviewsRows.emplace_back(HotelReviewsRow::ShowMore);
              length++;
            }

            self.sectionsAreReadyCallback({position, length}, self, YES /* It's a section */);
          });
        });
  });
}

#pragma mark - Update bookmark status

- (void)updateBookmarkStatus:(BOOL)isBookmark
{
  auto & f = GetFramework();
  auto & bmManager = f.GetBookmarkManager();
  if (isBookmark)
  {
    auto const categoryIndex = f.LastEditedBMCategory();
    BookmarkData bmData{m_info.FormatNewBookmarkName(), f.LastEditedBMType()};
    auto const bookmarkIndex = bmManager.AddBookmark(categoryIndex, self.mercator, bmData);

    auto category = f.GetBmCategory(categoryIndex);
    NSAssert(category, @"Category can't be nullptr!");
    auto bookmark = static_cast<Bookmark const *>(category->GetUserMark(bookmarkIndex));
    f.FillBookmarkInfo(*bookmark, {bookmarkIndex, categoryIndex}, m_info);
    category->NotifyChanges();
    m_sections.insert(m_sections.begin() + 1, Sections::Bookmark);
  }
  else
  {
    auto const bac = m_info.GetBookmarkAndCategory();
    auto category = bmManager.GetBmCategory(bac.m_categoryIndex);
    f.ResetBookmarkInfo(*static_cast<Bookmark const *>(category->GetUserMark(bac.m_bookmarkIndex)),
                        m_info);
    NSAssert(category, @"Category can't be nullptr!");
    category->DeleteUserMark(bac.m_bookmarkIndex);
    category->NotifyChanges();
    category->SaveToKMLFile();

    m_sections.erase(remove(m_sections.begin(), m_sections.end(), Sections::Bookmark));
  }
}

#pragma mark - Dealloc

- (void)dealloc
{
// TODO: Submit ugc.
//  [self.reviewViewModel submit];
  auto nativeAd = self.nativeAd;
  if (nativeAd)
    [[MWMBannersCache cache] bannerIsOutOfScreenWithCoreBanner:nativeAd];
}

#pragma mark - Getters

- (storage::TCountryId const &)countryId { return m_info.GetCountryId(); }
- (FeatureID const &)featureId { return m_info.GetID(); }
- (NSString *)title { return @(m_info.GetTitle().c_str()); }
- (NSString *)subtitle { return @(m_info.GetSubtitle().c_str()); }
- (place_page::OpeningHours)schedule;
{
  using type = place_page::OpeningHours;
  auto const raw = m_info.GetOpeningHours();
  if (raw.empty())
    return type::Unknown;

  auto const t = time(nullptr);
  osmoh::OpeningHours oh(raw);
  if (!oh.IsValid())
    return type::Unknown;
  if (oh.IsTwentyFourHours())
    return type::AllDay;
  if (oh.IsOpen(t))
    return type::Open;
  if (oh.IsClosed(t))
    return type::Closed;

  return type::Unknown;
}

#pragma mark - Sponsored

- (MWMUGCRatingValueType *)bookingRating
{
  if (!self.isBooking)
    return nil;
  auto const ratingRaw = m_info.GetRatingRawValue();
  return [[MWMUGCRatingValueType alloc]
      initWithValue:@(rating::GetRatingFormatted(ratingRaw).c_str())
               type:[MWMPlacePageData ratingValueType:rating::GetImpress(ratingRaw)]];
}
- (NSString *)bookingApproximatePricing { return self.isBooking ? @(m_info.GetApproximatePricing().c_str()) : nil; }
- (NSURL *)sponsoredURL
{
  if (m_info.IsSponsored())
  {
    auto urlString = [@(m_info.GetSponsoredUrl().c_str())
        stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet
                                                               .URLQueryAllowedCharacterSet];
    auto url = [NSURL URLWithString:urlString];
    return url;
  }
  return nil;
}

- (NSURL *)sponsoredDescriptionURL
{
  return m_info.IsSponsored()
             ? [NSURL URLWithString:@(m_info.GetSponsoredDescriptionUrl().c_str())]
             : nil;
}

- (NSURL *)bookingSearchURL
{
  auto const & url = m_info.GetBookingSearchUrl();
  return url.empty() ? nil : [NSURL URLWithString:@(url.c_str())];
}

- (NSString *)sponsoredId
{
  return m_info.IsSponsored()
             ? @(m_info.GetMetadata().Get(feature::Metadata::FMD_SPONSORED_ID).c_str())
             : nil;
}

- (void)assignOnlinePriceToLabel:(UILabel *)label
{
  NSAssert(self.isBooking, @"Online price must be assigned to booking object!");
  if (self.cachedMinPrice.length)
  {
    label.text = self.cachedMinPrice;
    return;
  }

  if (Platform::ConnectionStatus() == Platform::EConnectionType::CONNECTION_NONE)
    return;

  std::string const currency = self.currencyFormatter.currencyCode.UTF8String;

  auto const func = [self, label, currency](std::string const & hotelId, std::string const & minPrice,
                                            std::string const & priceCurrency) {
    if (currency != priceCurrency)
      return;

    NSNumberFormatter * decimalFormatter = [[NSNumberFormatter alloc] init];
    decimalFormatter.numberStyle = NSNumberFormatterDecimalStyle;

    NSNumber * currencyNumber = [decimalFormatter
        numberFromString:[@(minPrice.c_str())
                             stringByReplacingOccurrencesOfString:@"."
                                                       withString:decimalFormatter
                                                                      .decimalSeparator]];
    NSString * currencyString = [self.currencyFormatter stringFromNumber:currencyNumber];

    NSString * pattern =
        [L(@"place_page_starting_from") stringByReplacingOccurrencesOfString:@"%s"
                                                                  withString:@"%@"];

    self.cachedMinPrice = [NSString stringWithFormat:pattern, currencyString];
    dispatch_async(dispatch_get_main_queue(), ^{
      label.text = self.cachedMinPrice;
    });
  };

  network_policy::CallPartnersApi(
      [self, currency, func](platform::NetworkPolicy const & canUseNetwork) {
        auto const api = GetFramework().GetBookingApi(canUseNetwork);
        if (api)
          api->GetMinPrice(self.sponsoredId.UTF8String, currency, func);
      });
}

- (NSNumberFormatter *)currencyFormatter
{
  if (!_currencyFormatter)
  {
    _currencyFormatter = [[NSNumberFormatter alloc] init];
    if (_currencyFormatter.currencyCode.length != 3)
      _currencyFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    _currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
    _currencyFormatter.maximumFractionDigits = 0;
  }
  return _currencyFormatter;
}

- (NSString *)hotelDescription { return @(m_hotelInfo.m_description.c_str()); }
- (std::vector<booking::HotelFacility> const &)facilities { return m_hotelInfo.m_facilities; }
- (std::vector<booking::HotelReview> const &)hotelReviews { return m_hotelInfo.m_reviews; }
- (NSUInteger)numberOfHotelReviews { return m_hotelInfo.m_scoreCount; }

- (NSURL *)URLToAllReviews { return [NSURL URLWithString:@(m_info.GetSponsoredReviewUrl().c_str())]; }
- (NSArray<MWMGalleryItemModel *> *)photos
{
  if (_photos)
    return _photos;

  NSMutableArray<MWMGalleryItemModel *> * res = [@[] mutableCopy];
  for (auto const & p : m_hotelInfo.m_photos)
  {
    auto big = [NSURL URLWithString:@(p.m_original.c_str())];
    auto preview = [NSURL URLWithString:@(p.m_small.c_str())];
    if (!big || !preview)
      continue;
    
    auto photo = [[MWMGalleryItemModel alloc] initWithImageURL:big previewURL:preview];
    [res addObject:photo];
  }

  self.photos = res;
  return _photos;
}

#pragma mark - UGC

- (ftraits::UGCRatingCategories)ugcRatingCategories { return m_info.GetRatingCategories(); }

- (void)setUGCUpdateFrom:(MWMUGCReviewModel *)reviewModel
{
  using namespace ugc;
  auto appInfo = AppInfo.sharedInfo;
  auto const locale =
      static_cast<uint8_t>(StringUtf8Multilang::GetLangIndex(appInfo.twoLetterLanguageId.UTF8String));
  std::vector<uint8_t> keyboardLanguages;
  // TODO: Set the list of used keyboard languages (not only the recent one).
  auto lastInputLanguage = appInfo.twoLetterInputLanguage;
  keyboardLanguages.emplace_back(StringUtf8Multilang::GetLangIndex(lastInputLanguage.UTF8String));

  KeyboardText t{reviewModel.text.UTF8String, locale, keyboardLanguages};
  Ratings r;
  for (MWMUGCRatingStars * star in reviewModel.ratings)
    r.emplace_back(star.title.UTF8String, star.value);

  UGCUpdate update{r, t, std::chrono::system_clock::now()};
  auto & f = GetFramework();
  f.GetUGCApi()->SetUGCUpdate(m_info.GetID(), update);
  f.UpdatePlacePageInfoForCurrentSelection();
}

#pragma mark - Bookmark

- (NSString *)externalTitle
{
  return m_info.GetSecondaryTitle().empty() ? nil : @(m_info.GetSecondaryTitle().c_str());
}

- (NSString *)bookmarkColor
{
  return m_info.IsBookmark() ? @(m_info.GetBookmarkData().GetType().c_str()) : nil;
}

- (NSString *)bookmarkDescription
{
  return m_info.IsBookmark() ? @(m_info.GetBookmarkData().GetDescription().c_str()) : nil;
}

- (NSString *)bookmarkCategory
{
  return m_info.IsBookmark() ? @(m_info.GetBookmarkCategoryName().c_str()) : nil;
}

- (BookmarkAndCategory)bookmarkAndCategory
{
  return m_info.IsBookmark() ? m_info.GetBookmarkAndCategory() : BookmarkAndCategory();
}

#pragma mark - Local Ads
- (NSString *)localAdsURL { return @(m_info.GetLocalAdsUrl().c_str()); }
- (void)logLocalAdsEvent:(local_ads::EventType)type
{
  if (m_info.GetLocalAdsStatus() != place_page::LocalAdsStatus::Customer)
    return;
  auto const featureID = m_info.GetID();
  auto const & mwmInfo = featureID.m_mwmId.GetInfo();
  if (!mwmInfo)
    return;
  auto & f = GetFramework();
  auto location = [MWMLocationManager lastLocation];
  auto event = local_ads::Event(type, mwmInfo->GetVersion(), mwmInfo->GetCountryName(),
                                featureID.m_index, f.GetDrawScale(),
                                local_ads::Clock::now(), location.coordinate.latitude,
                                location.coordinate.longitude, location.horizontalAccuracy);
  f.GetLocalAdsManager().GetStatistics().RegisterEvent(std::move(event));
}

#pragma mark - Taxi
- (std::vector<taxi::Provider::Type> const &)taxiProviders
{
  return m_info.ReachableByTaxiProviders();
}

#pragma mark - Getters

- (RouteMarkType)routeMarkType { return m_info.GetRouteMarkType(); }
- (size_t)intermediateIndex { return m_info.GetIntermediateIndex(); }
- (NSString *)address { return @(m_info.GetAddress().c_str()); }
- (NSString *)apiURL { return @(m_info.GetApiUrl().c_str()); }
- (std::vector<Sections> const &)sections { return m_sections; }
- (std::vector<PreviewRows> const &)previewRows { return m_previewRows; }
- (std::vector<place_page::SpecialProject> const &)specialProjectRows
{
  return m_specialProjectRows;
}
- (std::vector<MetainfoRows> const &)metainfoRows { return m_metainfoRows; }
- (std::vector<MetainfoRows> &)mutableMetainfoRows { return m_metainfoRows; }
- (std::vector<AdRows> const &)adRows { return m_adRows; }
- (std::vector<ButtonsRows> const &)buttonsRows { return m_buttonsRows; }
- (std::vector<HotelPhotosRow> const &)photosRows { return m_hotelPhotosRows; }
- (std::vector<HotelDescriptionRow> const &)descriptionRows { return m_hotelDescriptionRows; }
- (std::vector<HotelFacilitiesRow> const &)hotelFacilitiesRows { return m_hotelFacilitiesRows; }
- (std::vector<HotelReviewsRow> const &)hotelReviewsRows { return m_hotelReviewsRows; }
- (NSString *)stringForRow:(MetainfoRows)row
{
  switch (row)
  {
  case MetainfoRows::ExtendedOpeningHours: return nil;
  case MetainfoRows::OpeningHours: return @(m_info.GetOpeningHours().c_str());
  case MetainfoRows::Phone: return @(m_info.GetPhone().c_str());
  case MetainfoRows::Address: return @(m_info.GetAddress().c_str());
  case MetainfoRows::Website: return @(m_info.GetWebsite().c_str());
  case MetainfoRows::Email: return @(m_info.GetEmail().c_str());
  case MetainfoRows::Cuisine:
    return @(strings::JoinStrings(m_info.GetLocalizedCuisines(), Info::kSubtitleSeparator).c_str());
  case MetainfoRows::Operator: return @(m_info.GetOperator().c_str());
  case MetainfoRows::Internet: return L(@"WiFi_available");
  case MetainfoRows::LocalAdsCandidate: return L(@"create_campaign_button");
  case MetainfoRows::LocalAdsCustomer: return L(@"view_campaign_button");
  case MetainfoRows::Coordinate:
    return @(m_info
                 .GetFormattedCoordinate(
                     [NSUserDefaults.standardUserDefaults boolForKey:kUserDefaultsLatLonAsDMSKey])
                 .c_str());
  }
}

#pragma mark - Helpres

- (NSString *)phoneNumber { return @(m_info.GetPhone().c_str()); }
- (BOOL)isBookmark { return m_info.IsBookmark(); }
- (BOOL)isApi { return m_info.HasApiUrl(); }
- (BOOL)isBooking { return m_info.GetSponsoredType() == SponsoredType::Booking; }
- (BOOL)isOpentable { return m_info.GetSponsoredType() == SponsoredType::Opentable; }
- (BOOL)isViator { return m_info.GetSponsoredType() == SponsoredType::Viator; }
- (BOOL)isCian { return m_info.GetSponsoredType() == SponsoredType::Cian; }
- (BOOL)isThor { return m_info.GetSponsoredType() == SponsoredType::Thor; }
- (BOOL)isHalloween { return m_info.GetSponsoredType() == SponsoredType::Halloween; }
- (BOOL)isBookingSearch { return !m_info.GetBookingSearchUrl().empty(); }
- (BOOL)isMyPosition { return m_info.IsMyPosition(); }
- (BOOL)isHTMLDescription { return strings::IsHTML(m_info.GetBookmarkData().GetDescription()); }
- (BOOL)isRoutePoint { return m_info.IsRoutePoint(); }

+ (MWMRatingSummaryViewValueType)ratingValueType:(rating::Impress)impress
{
  switch (impress)
  {
  case rating::Impress::None: return MWMRatingSummaryViewValueTypeNoValue;
  case rating::Impress::Horrible: return MWMRatingSummaryViewValueTypeHorrible;
  case rating::Impress::Bad: return MWMRatingSummaryViewValueTypeBad;
  case rating::Impress::Normal: return MWMRatingSummaryViewValueTypeNormal;
  case rating::Impress::Good: return MWMRatingSummaryViewValueTypeGood;
  case rating::Impress::Excellent: return MWMRatingSummaryViewValueTypeExcellent;
  }
}
#pragma mark - Coordinates

- (m2::PointD const &)mercator { return m_info.GetMercator(); }
- (ms::LatLon)latLon { return m_info.GetLatLon(); }
+ (void)toggleCoordinateSystem
{
  // TODO: Move changing latlon's mode to the settings.
  NSUserDefaults * ud = NSUserDefaults.standardUserDefaults;
  [ud setBool:![ud boolForKey:kUserDefaultsLatLonAsDMSKey] forKey:kUserDefaultsLatLonAsDMSKey];
  [ud synchronize];
}

#pragma mark - Stats

- (NSString *)statisticsTags
{
  NSMutableArray<NSString *> * result = [@[] mutableCopy];
  for (auto const & s : m_info.GetRawTypes())
    [result addObject:@(s.c_str())];
  return [result componentsJoinedByString:@", "];
}

@end