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

MWMBasePlacePageView.mm « Classes « Maps « iphone - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 16e3b99c654aeac47b77d3a0b6000e267be89e61 (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
#import "MWMBasePlacePageView.h"
#import "Common.h"
#import "MWMCircularProgress.h"
#import "MWMFrameworkListener.h"
#import "MWMLocationHelpers.h"
#import "MWMPlacePage.h"
#import "MWMPlacePageActionBar.h"
#import "MWMPlacePageBookmarkCell.h"
#import "MWMPlacePageButtonCell.h"
#import "MWMPlacePageEntity.h"
#import "MWMPlacePageInfoCell.h"
#import "MWMPlacePageOpeningHoursCell.h"
#import "MWMPlacePageViewManager.h"
#import "MWMStorage.h"
#import "MWMViewController.h"
#import "MapViewController.h"
#import "MapsAppDelegate.h"
#import "NSString+Categories.h"
#import "Statistics.h"
#import "UIColor+MapsMeColor.h"

#include "map/place_page_info.hpp"

#include "3party/opening_hours/opening_hours.hpp"
#include "editor/opening_hours_ui.hpp"
#include "editor/ui2oh.hpp"
#include "platform/local_country_file_utils.hpp"

namespace
{
CGFloat const kDownloadProgressViewLeftOffset = 12.;
CGFloat const kDownloadProgressViewTopOffset = 4.;
CGFloat const kLabelsBetweenMainOffset = 8.;
CGFloat const kLabelsBetweenSmallOffset = 4.;
CGFloat const kBottomPlacePageOffset = 16.;
CGFloat const kLeftOffset = 16.;
CGFloat const kDefaultHeaderHeight = 16.;
CGFloat const kLabelsPadding = kLeftOffset * 2;
CGFloat const kDirectionArrowSide = 20.;
CGFloat const kOffsetFromLabelsToDistance = 8.;
CGFloat const kOffsetFromDistanceToArrow = 5.;
CGFloat const kMaximumWidth = 360.;

enum class PlacePageSection
{
  Bookmark,
  Metadata,
  Editing,
  Booking
};

vector<MWMPlacePageCellType> const kSectionBookmarkCellTypes{MWMPlacePageCellTypeBookmark};

vector<MWMPlacePageCellType> const kSectionMetadataCellTypes{
    MWMPlacePageCellTypePostcode, MWMPlacePageCellTypePhoneNumber, MWMPlacePageCellTypeWebsite,
    MWMPlacePageCellTypeURL,      MWMPlacePageCellTypeEmail,       MWMPlacePageCellTypeOpenHours,
    MWMPlacePageCellTypeWiFi,     MWMPlacePageCellTypeCoordinate};

vector<MWMPlacePageCellType> const kSectionEditingCellTypes{MWMPlacePageCellTypeEditButton,
                                                            MWMPlacePageCellTypeAddBusinessButton,
                                                            MWMPlacePageCellTypeAddPlaceButton};

vector<MWMPlacePageCellType> const kSectionBookingCellTypes{MWMPlacePageCellTypeBookingMore};

using TCellTypesSectionMap = pair<vector<MWMPlacePageCellType>, PlacePageSection>;

vector<TCellTypesSectionMap> const kCellTypesSectionMap{
    {kSectionBookmarkCellTypes, PlacePageSection::Bookmark},
    {kSectionMetadataCellTypes, PlacePageSection::Metadata},
    {kSectionEditingCellTypes, PlacePageSection::Editing},
    {kSectionBookingCellTypes, PlacePageSection::Booking}};

MWMPlacePageCellTypeValueMap const kCellType2ReuseIdentifier{
    {MWMPlacePageCellTypeWiFi, "PlacePageInfoCell"},
    {MWMPlacePageCellTypeCoordinate, "PlacePageInfoCell"},
    {MWMPlacePageCellTypePostcode, "PlacePageInfoCell"},
    {MWMPlacePageCellTypeURL, "PlacePageLinkCell"},
    {MWMPlacePageCellTypeWebsite, "PlacePageLinkCell"},
    {MWMPlacePageCellTypeEmail, "PlacePageLinkCell"},
    {MWMPlacePageCellTypePhoneNumber, "PlacePageLinkCell"},
    {MWMPlacePageCellTypeOpenHours, "MWMPlacePageOpeningHoursCell"},
    {MWMPlacePageCellTypeBookmark, "PlacePageBookmarkCell"},
    {MWMPlacePageCellTypeEditButton, "MWMPlacePageButtonCell"},
    {MWMPlacePageCellTypeAddBusinessButton, "MWMPlacePageButtonCell"},
    {MWMPlacePageCellTypeAddPlaceButton, "MWMPlacePageButtonCell"},
    {MWMPlacePageCellTypeBookingMore, "MWMPlacePageButtonCell"}};

NSString * reuseIdentifier(MWMPlacePageCellType cellType)
{
  auto const it = kCellType2ReuseIdentifier.find(cellType);
  BOOL const haveCell = (it != kCellType2ReuseIdentifier.end());
  ASSERT(haveCell, ());
  return haveCell ? @(it->second.c_str()) : @"";
}

CGFloat placePageWidth()
{
  CGSize const size = UIScreen.mainScreen.bounds.size;
  return IPAD ? kMaximumWidth
              : (size.width > size.height ? MIN(kMaximumWidth, size.height) : size.width);
}

enum class AttributePosition
{
  Title,
  ExternalTitle,
  Subtitle,
  Schedule,
  Address
};
}  // namespace

using namespace storage;

@interface MWMBasePlacePageView ()<
    UITableViewDelegate, UITableViewDataSource, MWMPlacePageOpeningHoursCellProtocol,
    MWMPlacePageBookmarkDelegate, MWMCircularProgressProtocol, MWMFrameworkStorageObserver>
{
  vector<PlacePageSection> m_sections;
  map<PlacePageSection, vector<MWMPlacePageCellType>> m_cells;
  map<MWMPlacePageCellType, UITableViewCell *> m_offscreenCells;
}

@property(weak, nonatomic) MWMPlacePageEntity * entity;
@property(weak, nonatomic) IBOutlet MWMPlacePage * ownerPlacePage;

@property(nonatomic, readwrite) BOOL openingHoursCellExpanded;
@property(nonatomic) BOOL isBookmarkCellExpanded;

@property(nonatomic) MWMCircularProgress * mapDownloadProgress;
@property(nonatomic) TMwmSize downloadMapSize;

@end

@implementation MWMBasePlacePageView

- (void)awakeFromNib
{
  [super awakeFromNib];
  self.featureTable.delegate = self;
  self.featureTable.dataSource = self;
  self.featureTable.separatorColor = [UIColor blackDividers];

  for (auto const & type : kCellType2ReuseIdentifier)
  {
    NSString * identifier = @(type.second.c_str());
    [self.featureTable registerNib:[UINib nibWithNibName:identifier bundle:nil]
            forCellReuseIdentifier:identifier];
  }

  self.directionArrow.autoresizingMask = UIViewAutoresizingNone;
}

- (void)configureWithEntity:(MWMPlacePageEntity *)entity
{
  self.entity = entity;
  self.isBookmarkCellExpanded = NO;
  [self configTable];
  [self configure];
}

- (void)configTable
{
  m_sections.clear();
  m_cells.clear();
  m_offscreenCells.clear();
  for (auto const cellSection : kCellTypesSectionMap)
  {
    for (auto const cellType : cellSection.first)
    {
      if (![self.entity getCellValue:cellType])
        continue;
      m_sections.push_back(cellSection.second);
      m_cells[cellSection.second].push_back(cellType);
    }
  }

  sort(m_sections.begin(), m_sections.end());
  m_sections.erase(unique(m_sections.begin(), m_sections.end()), m_sections.end());
}

- (void)configure
{
  [self configureMapDownloader];

  MWMPlacePageEntity * entity = self.entity;
  if (entity.isBookmark)
  {
    if (![entity.bookmarkTitle isEqualToString:entity.title] && entity.bookmarkTitle.length > 0)
    {
      self.titleLabel.text = entity.bookmarkTitle;
      self.externalTitleLabel.text = entity.title;
    }
    else
    {
      self.titleLabel.text = entity.title;
      self.externalTitleLabel.text = @"";
    }
  }
  else
  {
    self.titleLabel.text = entity.title;
    self.externalTitleLabel.text = @"";
  }

  NSMutableString * subtitle = [entity.subtitle mutableCopy];
  NSString * sizeStr = self.downloadProgressView.hidden ? nil : formattedSize(self.downloadMapSize);
  if (subtitle)
  {
    NSString * separator = @(place_page::Info::kSubtitleSeparator);
    if (sizeStr)
      [subtitle appendString:[NSString stringWithFormat:@"%@%@", separator, sizeStr]];
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:subtitle];
    auto const separatorRanges = [subtitle rangesOfString:separator];
    if (!separatorRanges.empty())
    {
      for (auto const & r : separatorRanges)
        [str addAttributes:@{ NSForegroundColorAttributeName : [UIColor blackHintText] } range:r];
    }

    auto const starsRanges = [subtitle rangesOfString:@(place_page::Info::kStarSymbol)];
    if (!starsRanges.empty())
    {
      for (auto const & r : starsRanges)
        [str addAttributes:@{ NSForegroundColorAttributeName : [UIColor yellow] } range:r];
    }

    self.subtitleLabel.attributedText = str;
  }
  else
  {
    self.subtitleLabel.text = sizeStr;
  }

  BOOL const isMyPosition = entity.isMyPosition;
  self.addressLabel.text = entity.address;

  if (!entity.bookingOnlinePrice.length)
  {
    self.bookingPriceLabel.text = entity.bookingPrice;
    [entity onlinePricingWithCompletionBlock:^{
      if (!entity.bookingOnlinePrice.length)
        return;
      self.bookingPriceLabel.text = entity.bookingOnlinePrice;
      [self setNeedsLayout];
      [UIView animateWithDuration:kDefaultAnimationDuration
                       animations:^{
                         [self layoutIfNeeded];
                       }];
    }
                                     failure:^{
                                         // TODO(Vlad): Process an error.
                                     }];
  }
  else
  {
    self.bookingPriceLabel.text = entity.bookingOnlinePrice;
  }

  self.bookingRatingLabel.text = entity.bookingRating;
  self.bookingView.hidden = !entity.bookingPrice.length && !entity.bookingRating.length;
  BOOL const isHeadingAvaible = [CLLocationManager headingAvailable];
  BOOL const noLocation = location_helpers::isMyPositionPendingOrNoPosition();
  self.distanceLabel.hidden = noLocation || isMyPosition;
  BOOL const hideDirection = noLocation || isMyPosition || !isHeadingAvaible;
  self.directionArrow.hidden = hideDirection;
  self.directionButton.hidden = hideDirection;

  [self.featureTable reloadData];
  [self configureCurrentShedule];
  [MWMFrameworkListener addObserver:self];
  [self setNeedsLayout];
  [self layoutIfNeeded];
}

- (void)configureMapDownloader
{
  TCountryId const & countryId = self.entity.countryId;
  if (countryId == kInvalidCountryId || platform::migrate::NeedMigrate())
  {
    self.downloadProgressView.hidden = YES;
  }
  else
  {
    self.downloadProgressView.hidden = NO;
    [self setNeedsLayout];
    NodeAttrs nodeAttrs;
    GetFramework().GetStorage().GetNodeAttrs(countryId, nodeAttrs);
    MWMCircularProgress * progress = self.mapDownloadProgress;
    self.downloadMapSize = nodeAttrs.m_mwmSize - nodeAttrs.m_localMwmSize;
    switch (nodeAttrs.m_status)
    {
    case NodeStatus::NotDownloaded:
    case NodeStatus::Partly:
    {
      MWMCircularProgressStateVec const affectedStates = {MWMCircularProgressStateNormal,
                                                          MWMCircularProgressStateSelected};
      [progress setImage:[UIImage imageNamed:@"ic_download"] forStates:affectedStates];
      [progress setColoring:MWMButtonColoringBlue forStates:affectedStates];
      progress.state = MWMCircularProgressStateNormal;
      break;
    }
    case NodeStatus::Downloading:
    {
      auto const & prg = nodeAttrs.m_downloadingProgress;
      progress.progress = static_cast<CGFloat>(prg.first) / prg.second;
      break;
    }
    case NodeStatus::InQueue: progress.state = MWMCircularProgressStateSpinner; break;
    case NodeStatus::Undefined:
    case NodeStatus::Error: progress.state = MWMCircularProgressStateFailed; break;
    case NodeStatus::OnDisk:
    case NodeStatus::OnDiskOutOfDate:
    {
      self.downloadProgressView.hidden = YES;
      [self setNeedsLayout];
      [UIView animateWithDuration:kDefaultAnimationDuration
                       animations:^{
                         [self layoutIfNeeded];
                       }];
      break;
    }
    }
  }
}

- (void)configureCurrentShedule
{
  MWMPlacePageOpeningHoursCell * cell =
      static_cast<MWMPlacePageOpeningHoursCell *>(m_offscreenCells[MWMPlacePageCellTypeOpenHours]);
  if (cell)
  {
    self.placeScheduleLabel.text = cell.isClosed ? L(@"closed_now") : L(@"editor_time_open");
    self.placeScheduleLabel.textColor =
        cell.isClosed ? [UIColor red] : [UIColor blackSecondaryText];
  }
  else
  {
    self.placeScheduleLabel.text = @"";
  }
}

#pragma mark - Layout

- (AttributePosition)distanceAttributePosition
{
  if (self.addressLabel.text.length)
    return AttributePosition::Address;
  else if (!self.addressLabel.text.length && self.placeScheduleLabel.text.length)
    return AttributePosition::Schedule;
  else if (!self.placeScheduleLabel.text.length && self.subtitleLabel.text.length)
    return AttributePosition::Subtitle;
  else if (self.externalTitleLabel.text.length)
    return AttributePosition::ExternalTitle;
  else
    return AttributePosition::Title;
}

- (void)setupLabelsWidthWithBoundedWidth:(CGFloat)bound distancePosition:(AttributePosition)position
{
  auto const defaultMaxWidth = placePageWidth() - kLabelsPadding;
  CGFloat const labelsMaxWidth =
      self.downloadProgressView.hidden
          ? defaultMaxWidth
          : defaultMaxWidth - 2 * kDownloadProgressViewLeftOffset - self.downloadProgressView.width;
  switch (position)
  {
  case AttributePosition::Title:
    self.titleLabel.width = labelsMaxWidth - bound;
    self.subtitleLabel.width = self.addressLabel.width = self.externalTitleLabel.width =
        self.placeScheduleLabel.width = 0;
    break;
  case AttributePosition::ExternalTitle:
    self.addressLabel.width = self.subtitleLabel.width = self.placeScheduleLabel.width = 0;
    self.externalTitleLabel.width = labelsMaxWidth - bound;
    self.titleLabel.width = self.titleLabel.text.length > 0 ? labelsMaxWidth : 0;
    break;
  case AttributePosition::Subtitle:
    self.addressLabel.width = self.placeScheduleLabel.width = 0;
    self.titleLabel.width = self.titleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.externalTitleLabel.width = self.externalTitleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.subtitleLabel.width = labelsMaxWidth - bound;
    break;
  case AttributePosition::Schedule:
    self.addressLabel.width = 0;
    self.titleLabel.width = self.titleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.externalTitleLabel.width = self.externalTitleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.subtitleLabel.width = self.subtitleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.placeScheduleLabel.width = labelsMaxWidth - bound;
    break;
  case AttributePosition::Address:
    self.titleLabel.width = self.titleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.subtitleLabel.width = self.subtitleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.externalTitleLabel.width = self.externalTitleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.placeScheduleLabel.width = self.placeScheduleLabel.text.length > 0 ? labelsMaxWidth : 0;
    self.addressLabel.width = labelsMaxWidth - bound;
    break;
  }

  self.externalTitleLabel.width = self.entity.isBookmark ? labelsMaxWidth : 0;

  CGFloat const bookingWidth = labelsMaxWidth / 2;
  self.bookingRatingLabel.width = bookingWidth;
  self.bookingPriceLabel.width = bookingWidth - kLabelsBetweenSmallOffset;
  self.bookingView.width = labelsMaxWidth;

  [self.titleLabel sizeToFit];
  [self.subtitleLabel sizeToFit];
  [self.addressLabel sizeToFit];
  [self.externalTitleLabel sizeToFit];
  [self.placeScheduleLabel sizeToFit];
  [self.bookingRatingLabel sizeToFit];
  [self.bookingPriceLabel sizeToFit];
}

- (void)setDistance:(NSString *)distance
{
  self.distanceLabel.text = distance;
  self.distanceLabel.width = placePageWidth() - kLabelsPadding;
  [self.distanceLabel sizeToFit];
  [self layoutDistanceBoxWithPosition:[self distanceAttributePosition]];
}

- (void)layoutSubviews
{
  [super layoutSubviews];
  CGFloat const bound = self.distanceLabel.width + kDirectionArrowSide +
                        kOffsetFromDistanceToArrow + kOffsetFromLabelsToDistance;
  AttributePosition const position = [self distanceAttributePosition];
  [self setupLabelsWidthWithBoundedWidth:bound distancePosition:position];
  [self setupBookingView];
  [self layoutLabelsAndBooking];
  [self layoutTableViewWithPosition:position];
  [self setDistance:self.distanceLabel.text];
  self.height = self.featureTable.height + self.ppPreview.height;
}

- (void)setupBookingView
{
  self.bookingRatingLabel.origin = {};
  self.bookingPriceLabel.origin = {self.bookingView.width - self.bookingPriceLabel.width, 0};
  self.bookingSeparator.origin = {0, self.bookingRatingLabel.maxY + kLabelsBetweenMainOffset};
  self.bookingView.height = self.bookingSeparator.maxY + kLabelsBetweenMainOffset;
}

- (void)layoutLabelsAndBooking
{
  BOOL const isDownloadProgressViewHidden = self.downloadProgressView.hidden;
  if (!isDownloadProgressViewHidden)
    self.downloadProgressView.origin = {kDownloadProgressViewLeftOffset,
                                        kDownloadProgressViewTopOffset};

  CGFloat const leftOffset = isDownloadProgressViewHidden
                                 ? kLeftOffset
                                 : self.downloadProgressView.maxX + kDownloadProgressViewLeftOffset;

  auto originFrom = ^CGPoint(UIView * v, BOOL isBigOffset) {
    CGFloat const offset = isBigOffset ? kLabelsBetweenMainOffset : kLabelsBetweenSmallOffset;
    if ([v isKindOfClass:[UILabel class]])
      return {leftOffset, (static_cast<UILabel *>(v).text.length == 0 ? v.minY : v.maxY) + offset};
    return {leftOffset, v.hidden ? v.minY : v.maxY + offset};
  };

  self.titleLabel.origin = {leftOffset, kLabelsBetweenSmallOffset};
  self.externalTitleLabel.origin = originFrom(self.titleLabel, NO);
  self.subtitleLabel.origin = originFrom(self.externalTitleLabel, NO);
  self.placeScheduleLabel.origin = originFrom(self.subtitleLabel, NO);
  self.bookingView.origin = originFrom(self.placeScheduleLabel, NO);
  self.addressLabel.origin = originFrom(self.bookingView, YES);
}

- (void)layoutDistanceBoxWithPosition:(AttributePosition)position
{
  auto getY = ^CGFloat(AttributePosition p) {
    // Have to align distance box for the first label's line.
    CGFloat const defaultCenter = p == AttributePosition::Title ? 12 : 8;
    switch (position)
    {
    case AttributePosition::Title: return self.titleLabel.minY + defaultCenter;
    case AttributePosition::ExternalTitle: return self.externalTitleLabel.minY + defaultCenter;
    case AttributePosition::Subtitle: return self.subtitleLabel.minY + defaultCenter;
    case AttributePosition::Schedule: return self.placeScheduleLabel.minY + defaultCenter;
    case AttributePosition::Address: return self.addressLabel.minY + defaultCenter;
    }
  };

  CGFloat const distanceX = placePageWidth() - kLeftOffset - self.distanceLabel.width;
  CGFloat const directionX = distanceX - kOffsetFromDistanceToArrow - kDirectionArrowSide;
  CGFloat const y = getY(position);
  CGPoint const center = {directionX + kDirectionArrowSide / 2, y};
  self.directionArrow.center = center;
  self.directionButton.origin = {center.x - self.directionButton.width / 2,
                                 center.y - self.directionButton.height / 2};
  self.distanceLabel.center = {distanceX + self.distanceLabel.width / 2,
                               self.directionArrow.center.y};
}

- (void)layoutTableViewWithPosition:(AttributePosition)position
{
  auto getY = ^CGFloat(AttributePosition p) {
    if (self.bookingView.hidden)
    {
      switch (position)
      {
      case AttributePosition::Title: return self.titleLabel.maxY + kBottomPlacePageOffset;
      case AttributePosition::ExternalTitle:
        return self.externalTitleLabel.maxY + kBottomPlacePageOffset;
      case AttributePosition::Subtitle: return self.subtitleLabel.maxY + kBottomPlacePageOffset;
      case AttributePosition::Schedule:
        return self.placeScheduleLabel.maxY + kBottomPlacePageOffset;
      case AttributePosition::Address: return self.addressLabel.maxY + kBottomPlacePageOffset;
      }
    }
    else
    {
      switch (position)
      {
      case AttributePosition::Title:
      case AttributePosition::ExternalTitle:
      case AttributePosition::Subtitle:
      case AttributePosition::Schedule: return self.bookingView.maxY + kBottomPlacePageOffset;
      case AttributePosition::Address: return self.addressLabel.maxY + kBottomPlacePageOffset;
      }
    }
  };

  self.separatorView.minY = getY(position);
  self.ppPreview.frame = {{}, {self.ppPreview.superview.width, self.separatorView.maxY}};
  self.featureTable.minY = self.separatorView.maxY;
  self.featureTable.height = self.featureTable.contentSize.height;
}

#pragma mark - Actions

- (void)addBookmark
{
  [Statistics logEvent:kStatEventName(kStatPlacePage, kStatToggleBookmark)
        withParameters:@{kStatValue : kStatAdd}];
  [self.subtitleLabel sizeToFit];

  m_sections.push_back(PlacePageSection::Bookmark);
  m_cells[PlacePageSection::Bookmark].push_back(MWMPlacePageCellTypeBookmark);
  sort(m_sections.begin(), m_sections.end());
  [self configure];
}

- (void)removeBookmark
{
  [Statistics logEvent:kStatEventName(kStatPlacePage, kStatToggleBookmark)
        withParameters:@{kStatValue : kStatRemove}];

  auto const it = find(m_sections.begin(), m_sections.end(), PlacePageSection::Bookmark);
  if (it != m_sections.end())
  {
    m_sections.erase(it);
    m_cells.erase(PlacePageSection::Bookmark);
  }

  m_offscreenCells.erase(MWMPlacePageCellTypeBookmark);

  [self configure];
}

- (void)reloadBookmarkCell
{
  MWMPlacePageCellType const type = MWMPlacePageCellTypeBookmark;
  [self fillCell:m_offscreenCells[type] withType:type];
  [self configure];
  [CATransaction begin];
  [CATransaction setCompletionBlock:^{
    [self setNeedsLayout];
    dispatch_async(dispatch_get_main_queue(), ^{
      [self.ownerPlacePage refresh];
    });
  }];
  [CATransaction commit];
}

- (IBAction)directionButtonTap
{
  [Statistics logEvent:kStatEventName(kStatPlacePage, kStatCompass)];
  [self.ownerPlacePage.manager showDirectionViewWithTitle:self.titleLabel.text
                                                     type:self.subtitleLabel.text];
}

- (void)updateAndLayoutMyPositionSpeedAndAltitude:(NSString *)text
{
  self.subtitleLabel.text = text;
  [self setNeedsLayout];
}

#pragma mark - MWMPlacePageBookmarkDelegate

- (void)reloadBookmark { [self reloadBookmarkCell]; }
- (void)editBookmarkTap { [self.ownerPlacePage editBookmark]; }
- (void)moreTap
{
  self.isBookmarkCellExpanded = YES;
  [self reloadBookmarkCell];
}

#pragma mark - MWMPlacePageOpeningHoursCellProtocol

- (BOOL)forcedButton { return NO; }
- (BOOL)isPlaceholder { return NO; }
- (BOOL)isEditor { return NO; }
- (void)setOpeningHoursCellExpanded:(BOOL)openingHoursCellExpanded
{
  _openingHoursCellExpanded = openingHoursCellExpanded;
  UITableView * tv = self.featureTable;
  MWMPlacePageCellType const type = MWMPlacePageCellTypeOpenHours;
  [self fillCell:m_offscreenCells[MWMPlacePageCellTypeOpenHours] withType:type];
  [tv beginUpdates];
  [CATransaction begin];
  [CATransaction setCompletionBlock:^{
    [self setNeedsLayout];
    dispatch_async(dispatch_get_main_queue(), ^{
      [self.ownerPlacePage refresh];
    });
  }];
  [tv endUpdates];
  [CATransaction commit];
}

- (UITableViewCell *)offscreenCellForCellType:(MWMPlacePageCellType)type
{
  UITableViewCell * cell = m_offscreenCells[type];
  if (!cell)
  {
    NSString * identifier = reuseIdentifier(type);
    cell = [[[NSBundle mainBundle] loadNibNamed:identifier owner:nil options:nil] firstObject];
    [self fillCell:cell withType:type];
    m_offscreenCells[type] = cell;
  }
  return cell;
}

#pragma mark - UITableView

- (MWMPlacePageCellType)cellTypeForIndexPath:(NSIndexPath *)indexPath
{
  return [self cellsForSection:indexPath.section][indexPath.row];
}

- (NSString *)cellIdentifierForIndexPath:(NSIndexPath *)indexPath
{
  MWMPlacePageCellType const cellType = [self cellTypeForIndexPath:indexPath];
  return reuseIdentifier(cellType);
}

- (void)fillCell:(UITableViewCell *)cell withType:(MWMPlacePageCellType)cellType
{
  MWMPlacePageEntity * entity = self.entity;
  switch (cellType)
  {
  case MWMPlacePageCellTypeBookmark:
    [static_cast<MWMPlacePageBookmarkCell *>(cell) configWithText:entity.bookmarkDescription
                                                         delegate:self
                                                   placePageWidth:placePageWidth()
                                                           isOpen:self.isBookmarkCellExpanded
                                                           isHtml:entity.isHTMLDescription];
    break;
  case MWMPlacePageCellTypeOpenHours:
    [(MWMPlacePageOpeningHoursCell *)cell configWithDelegate:self
                                                        info:[entity getCellValue:cellType]];
    break;
  case MWMPlacePageCellTypeEditButton:
  case MWMPlacePageCellTypeAddBusinessButton:
  case MWMPlacePageCellTypeAddPlaceButton:
  case MWMPlacePageCellTypeBookingMore:
    [static_cast<MWMPlacePageButtonCell *>(cell) config:self.ownerPlacePage.manager
                                                forType:cellType];
    break;
  default:
  {
    MWMPlacePageInfoCell * tCell = (MWMPlacePageInfoCell *)cell;
    tCell.currentEntity = entity;
    [tCell configureWithType:cellType info:[entity getCellValue:cellType]];
    break;
  }
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  MWMPlacePageCellType const cellType = [self cellTypeForIndexPath:indexPath];
  UITableViewCell * cell = [self offscreenCellForCellType:cellType];
  switch (cellType)
  {
  case MWMPlacePageCellTypeBookmark: return ((MWMPlacePageBookmarkCell *)cell).cellHeight;
  case MWMPlacePageCellTypeOpenHours: return ((MWMPlacePageOpeningHoursCell *)cell).cellHeight;
  default:
  {
    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];
    cell.bounds = {{}, {CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds)}};
    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    CGSize const size =
        [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height;
  }
  }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [self cellsForSection:section].size();
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return m_sections.size(); }
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  MWMPlacePageCellType const type = [self cellTypeForIndexPath:indexPath];
  NSString * identifier = reuseIdentifier(type);
  UITableViewCell * cell = m_offscreenCells[type];
  if (!cell)
    cell = [tableView dequeueReusableCellWithIdentifier:identifier];

  return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
  return section == m_sections.size() - 1 ? kDefaultHeaderHeight : 0.;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
  if (m_sections[section] == PlacePageSection::Bookmark)
    return 0.001;
  return kDefaultHeaderHeight;
}

- (vector<MWMPlacePageCellType>)cellsForSection:(NSInteger)section
{
  NSAssert(m_sections.size() > section, @"Invalid section");
  return m_cells[m_sections[section]];
}

#pragma mark - MWMFrameworkStorageObserver

- (void)processCountryEvent:(TCountryId const &)countryId
{
  if (countryId != self.entity.countryId)
    return;
  [self configureMapDownloader];
}

- (void)processCountry:(TCountryId const &)countryId
              progress:(MapFilesDownloader::TProgress const &)progress
{
  if (countryId != self.entity.countryId)
    return;
  self.mapDownloadProgress.progress = static_cast<CGFloat>(progress.first) / progress.second;
}

#pragma mark - MWMCircularProgressProtocol

- (void)progressButtonPressed:(nonnull MWMCircularProgress *)progress
{
  TCountryId const & countryId = self.entity.countryId;
  NodeAttrs nodeAttrs;
  GetFramework().GetStorage().GetNodeAttrs(countryId, nodeAttrs);
  MWMAlertViewController * avc = self.ownerPlacePage.manager.ownerViewController.alertController;
  switch (nodeAttrs.m_status)
  {
  case NodeStatus::NotDownloaded:
  case NodeStatus::Partly:
    [MWMStorage downloadNode:countryId alertController:avc onSuccess:nil];
    break;
  case NodeStatus::Undefined:
  case NodeStatus::Error: [MWMStorage retryDownloadNode:countryId]; break;
  case NodeStatus::OnDiskOutOfDate: [MWMStorage updateNode:countryId alertController:avc]; break;
  case NodeStatus::Downloading:
  case NodeStatus::InQueue: [MWMStorage cancelDownloadNode:countryId]; break;
  case NodeStatus::OnDisk: break;
  }
}

#pragma mark - Properties

- (MWMCircularProgress *)mapDownloadProgress
{
  if (!_mapDownloadProgress)
  {
    _mapDownloadProgress =
        [MWMCircularProgress downloaderProgressForParentView:self.downloadProgressView];
    _mapDownloadProgress.delegate = self;
  }
  return _mapDownloadProgress;
}

@end