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

MapsAppDelegate.mm « Classes « Maps « iphone - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1ee55ebf59eae18af7005b981e405bf076945493 (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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
#import "MapsAppDelegate.h"
#import <CoreSpotlight/CoreSpotlight.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "3party/Alohalytics/src/alohalytics_objc.h"
#import "EAGLView.h"
#import "LocalNotificationManager.h"
#import "MWMAuthorizationCommon.h"
#import "MWMCommon.h"
#import "MWMCoreRouterType.h"
#import "MWMFrameworkListener.h"
#import "MWMFrameworkObservers.h"
#import "MWMMapViewControlsManager.h"
#import "MWMPushNotifications.h"
#import "MWMRoutePoint+CPP.h"
#import "MWMRouter.h"
#import "MWMSearch+CoreSpotlight.h"
#import "MWMTextToSpeech.h"
#import "MapViewController.h"
#import "Statistics.h"
#import "SwiftBridge.h"

#include "Framework.h"

#include "map/gps_tracker.hpp"

#include "platform/http_thread_apple.h"
#include "platform/local_country_file_utils.hpp"

// If you have a "missing header error" here, then please run configure.sh script in the root repo
// folder.
#import "private.h"

#ifdef OMIM_PRODUCTION

#import <AppsFlyerTracker/AppsFlyerTracker.h>
#import <Crashlytics/Crashlytics.h>
#import <Fabric/Fabric.h>

#endif

extern NSString * const MapsStatusChangedNotification = @"MapsStatusChangedNotification";
// Alert keys.
extern NSString * const kUDAlreadyRatedKey = @"UserAlreadyRatedApp";
extern NSString * const kUDAlreadySharedKey = @"UserAlreadyShared";

namespace
{
NSString * const kUDLastLaunchDateKey = @"LastLaunchDate";
NSString * const kUDSessionsCountKey = @"SessionsCount";
NSString * const kUDFirstVersionKey = @"FirstVersion";
NSString * const kUDLastRateRequestDate = @"LastRateRequestDate";
NSString * const kUDLastShareRequstDate = @"LastShareRequestDate";
NSString * const kUDAutoNightModeOff = @"AutoNightModeOff";
NSString * const kIOSIDFA = @"IFA";
NSString * const kBundleVersion = @"BundleVersion";

/// Adds needed localized strings to C++ code
/// @TODO Refactor localization mechanism to make it simpler
void InitLocalizedStrings()
{
  Framework & f = GetFramework();

  f.AddString("core_entrance", L(@"core_entrance").UTF8String);
  f.AddString("core_exit", L(@"core_exit").UTF8String);
  f.AddString("core_my_places", L(@"core_my_places").UTF8String);
  f.AddString("core_my_position", L(@"core_my_position").UTF8String);
  f.AddString("core_placepage_unknown_place", L(@"core_placepage_unknown_place").UTF8String);
  f.AddString("wifi", L(@"wifi").UTF8String);
}

void InitCrashTrackers()
{
#ifdef OMIM_PRODUCTION
  if ([MWMSettings crashReportingDisabled])
    return;

  NSString * fabricKey = @(CRASHLYTICS_IOS_KEY);
  if (fabricKey.length != 0)
  {
    // Initialize Fabric/Crashlytics SDK.
    [Fabric with:@[ [Crashlytics class] ]];
  }
#endif
}

void ConfigCrashTrackers()
{
#ifdef OMIM_PRODUCTION
  [[Crashlytics sharedInstance] setObjectValue:[Alohalytics installationId]
                                        forKey:@"AlohalyticsInstallationId"];
#endif
}

void OverrideUserAgent()
{
  [NSUserDefaults.standardUserDefaults registerDefaults:@{
    @"UserAgent" : @"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.30 "
                   @"(KHTML, like Gecko) Version/10.0 Mobile/14E269 Safari/602.1"
  }];
}
  
void InitMarketingTrackers()
{
#ifdef OMIM_PRODUCTION
  NSString * appsFlyerDevKey = @(APPSFLYER_KEY);
  NSString * appsFlyerAppIdKey = @(APPSFLYER_APP_ID_IOS);
  if (appsFlyerDevKey.length != 0 && appsFlyerAppIdKey.length != 0)
  {
    [AppsFlyerTracker sharedTracker].appsFlyerDevKey = appsFlyerDevKey;
    [AppsFlyerTracker sharedTracker].appleAppID = appsFlyerAppIdKey;
  }
#endif
}

void TrackMarketingAppLaunch()
{
#ifdef OMIM_PRODUCTION
  [[AppsFlyerTracker sharedTracker] trackAppLaunch];
#endif
}
}  // namespace

using namespace osm_auth_ios;

@interface MapsAppDelegate ()<MWMFrameworkStorageObserver>

@property(nonatomic) NSInteger standbyCounter;
@property(nonatomic) MWMBackgroundFetchScheduler * backgroundFetchScheduler;

@end

@implementation MapsAppDelegate
{
  NSString * m_geoURL;
  NSString * m_mwmURL;
  NSString * m_fileURL;

  NSString * m_scheme;
  NSString * m_sourceApplication;
}

+ (MapsAppDelegate *)theApp
{
  return (MapsAppDelegate *)UIApplication.sharedApplication.delegate;
}

#pragma mark - Notifications

// system push notification registration success callback, delegate to pushManager
- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [MWMPushNotifications application:application
      didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// system push notification registration error callback, delegate to pushManager
- (void)application:(UIApplication *)application
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [MWMPushNotifications application:application
      didFailToRegisterForRemoteNotificationsWithError:error];
}

// system push notifications callback, delegate to pushManager
- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo
          fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [MWMPushNotifications application:application
       didReceiveRemoteNotification:userInfo
             fetchCompletionHandler:completionHandler];
}

- (BOOL)isDrapeEngineCreated
{
  return ((EAGLView *)self.mapViewController.view).drapeEngineCreated;
}

- (BOOL)hasApiURL { return m_geoURL || m_mwmURL; }
- (void)handleURLs
{
  static_cast<EAGLView *>(self.mapViewController.view).isLaunchByDeepLink = self.hasApiURL;

  if (!self.isDrapeEngineCreated)
  {
    dispatch_async(dispatch_get_main_queue(), ^{
      [self handleURLs];
    });
    return;
  }

  Framework & f = GetFramework();
  if (m_geoURL)
  {
    if (f.ShowMapForURL(m_geoURL.UTF8String))
    {
      [Statistics logEvent:kStatEventName(kStatApplication, kStatImport)
            withParameters:@{kStatValue : m_scheme}];
      [self showMap];
    }
  }
  else if (m_mwmURL)
  {
    using namespace url_scheme;

    string const url = m_mwmURL.UTF8String;
    auto const parsingType = f.ParseAndSetApiURL(url);
    NSLog(@"Started by url: %@", m_mwmURL);
    switch (parsingType)
    {
    case ParsedMapApi::ParsingResult::Incorrect:
      LOG(LWARNING, ("Incorrect parsing result for url:", url));
      break;
    case ParsedMapApi::ParsingResult::Route:
    {
      auto const parsedData = f.GetParsedRoutingData();
      auto const points = parsedData.m_points;
      if (points.size() == 2)
      {
        auto p1 = [[MWMRoutePoint alloc] initWithURLSchemeRoutePoint:points.front()
                                                                type:MWMRoutePointTypeStart
                                                   intermediateIndex:0];
        auto p2 = [[MWMRoutePoint alloc] initWithURLSchemeRoutePoint:points.back()
                                                                type:MWMRoutePointTypeFinish
                                                   intermediateIndex:0];
        [MWMRouter buildApiRouteWithType:routerType(parsedData.m_type)
                              startPoint:p1
                             finishPoint:p2];
      }
      else
      {
#ifdef OMIM_PRODUCTION
        auto err = [[NSError alloc] initWithDomain:kMapsmeErrorDomain
                                              code:5
                                          userInfo:@{
                                            @"Description" : @"Invalid number of route points",
                                            @"URL" : m_mwmURL
                                          }];
        [[Crashlytics sharedInstance] recordError:err];
#endif
      }

      [self showMap];
      break;
    }
    case ParsedMapApi::ParsingResult::Map:
      if (f.ShowMapForURL(url))
        [self showMap];
      break;
    case ParsedMapApi::ParsingResult::Search:
    {
      auto const & request = f.GetParsedSearchRequest();
      auto manager = [MWMMapViewControlsManager manager];

      auto query = [@((request.m_query + " ").c_str()) stringByRemovingPercentEncoding];
      auto locale = @(request.m_locale.c_str());

      if (request.m_isSearchOnMap)
        [manager searchTextOnMap:query forInputLocale:locale];
      else
        [manager searchText:query forInputLocale:locale];

      break;
    }
    case ParsedMapApi::ParsingResult::Catalogue:
      [self.mapViewController openCatalogDeeplink:[[NSURL alloc] initWithString:m_mwmURL] animated:NO];
      break;
    case ParsedMapApi::ParsingResult::Lead: break;
    }
  }
  else if (m_fileURL)
  {
    f.AddBookmarksFile(m_fileURL.UTF8String, false /* isTemporaryFile */);
  }
  else
  {
    // Take a copy of pasteboard string since it can accidentally become nil while we still use it.
    NSString * pasteboard = [[UIPasteboard generalPasteboard].string copy];
    if (pasteboard && pasteboard.length)
    {
      if (f.ShowMapForURL(pasteboard.UTF8String))
      {
        [self showMap];
        [UIPasteboard generalPasteboard].string = @"";
      }
    }
  }
  m_geoURL = nil;
  m_mwmURL = nil;
  m_fileURL = nil;
}

- (NSURL *)convertUniversalLink:(NSURL *)universalLink
{
  auto deeplink = [NSString stringWithFormat:@"mapsme://%@?%@", universalLink.path, universalLink.query];
  return [NSURL URLWithString:deeplink];
}

- (void)searchText:(NSString *)searchString
{
  if (!self.isDrapeEngineCreated)
  {
    dispatch_async(dispatch_get_main_queue(), ^{ [self searchText:searchString]; });
    return;
  }

  [[MWMMapViewControlsManager manager] searchText:[searchString stringByAppendingString:@" "]
                                   forInputLocale:[MWMSettings spotlightLocaleLanguageId]];
}

- (void)incrementSessionsCountAndCheckForAlert
{
  [self incrementSessionCount];
  [self showAlertIfRequired];
}

- (void)commonInit
{
  [HttpThread setDownloadIndicatorProtocol:self];
  InitLocalizedStrings();
  GetFramework().SetupMeasurementSystem();
  [MWMFrameworkListener addObserver:self];
  [MapsAppDelegate customizeAppearance];

  self.standbyCounter = 0;
  NSTimeInterval const minimumBackgroundFetchIntervalInSeconds = 6 * 60 * 60;
  [UIApplication.sharedApplication
      setMinimumBackgroundFetchInterval:minimumBackgroundFetchIntervalInSeconds];
  [MWMMyTarget startAdServerForbiddenCheckTimer];
  [self updateApplicationIconBadgeNumber];
}

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  OverrideUserAgent();

  InitCrashTrackers();
  
  InitMarketingTrackers();

  // Initialize all 3party engines.
  BOOL returnValue = [self initStatistics:application didFinishLaunchingWithOptions:launchOptions];

  // We send Alohalytics installation id to Fabric.
  // To make sure id is created, ConfigCrashTrackers must be called after Statistics initialization.
  ConfigCrashTrackers();

  NSURL * urlUsedToLaunchMaps = launchOptions[UIApplicationLaunchOptionsURLKey];
  if (urlUsedToLaunchMaps != nil)
    returnValue |= [self checkLaunchURL:urlUsedToLaunchMaps];
  else
    returnValue = YES;

  [HttpThread setDownloadIndicatorProtocol:self];

  InitLocalizedStrings();
  [MWMThemeManager invalidate];

  [self commonInit];

  LocalNotificationManager * notificationManager = [LocalNotificationManager sharedManager];
  if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey])
    [notificationManager
        processNotification:launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]
                   onLaunch:YES];

  if ([Alohalytics isFirstSession])
  {
    [self firstLaunchSetup];
  }
  else
  {
    if ([MWMSettings statisticsEnabled])
      [Alohalytics enable];
    else
      [Alohalytics disable];
    [self incrementSessionsCountAndCheckForAlert];

    //For first launch setup is called by FirstLaunchController
    [MWMPushNotifications setup:launchOptions];
  }
  [self enableTTSForTheFirstTime];

  [MWMRouter restoreRouteIfNeeded];

  [GIDSignIn sharedInstance].clientID =
      [[NSBundle mainBundle] loadWithPlist:@"GoogleService-Info"][@"CLIENT_ID"];

  return returnValue;
}

- (void)application:(UIApplication *)application
    performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem
               completionHandler:(void (^)(BOOL))completionHandler
{
  [self.mapViewController performAction:shortcutItem.type];
  completionHandler(YES);
}

- (void)runBackgroundTasks:(NSArray<BackgroundFetchTask *> * _Nonnull)tasks
         completionHandler:(void (^_Nullable)(UIBackgroundFetchResult))completionHandler
{
  auto completion = ^(UIBackgroundFetchResult result) {
    if (completionHandler)
      completionHandler(result);
  };
  self.backgroundFetchScheduler =
      [[MWMBackgroundFetchScheduler alloc] initWithTasks:tasks completionHandler:completion];
  [self.backgroundFetchScheduler run];
}

- (void)application:(UIApplication *)application
    performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  auto tasks = @[
    [[MWMBackgroundStatisticsUpload alloc] init], [[MWMBackgroundEditsUpload alloc] init],
    [[MWMBackgroundUGCUpload alloc] init], [[MWMBackgroundDownloadMapNotification alloc] init]
  ];

  [self runBackgroundTasks:tasks completionHandler:completionHandler];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
#ifdef OMIM_PRODUCTION
  auto err = [[NSError alloc] initWithDomain:kMapsmeErrorDomain
                                        code:1
                                    userInfo:@{
                                      @"Description" : @"applicationDidReceiveMemoryWarning"
                                    }];
  [[Crashlytics sharedInstance] recordError:err];
#endif
}

- (void)applicationWillTerminate:(UIApplication *)application
{
  [self.mapViewController onTerminate];

#ifdef OMIM_PRODUCTION
  auto err = [[NSError alloc] initWithDomain:kMapsmeErrorDomain
                                        code:2
                                    userInfo:@{
                                      @"Description" : @"applicationWillTerminate"
                                    }];
  [[Crashlytics sharedInstance] recordError:err];
#endif

  // Global cleanup
  DeleteFramework();
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
  LOG(LINFO, ("applicationDidEnterBackground - begin"));
  if (m_activeDownloadsCounter)
  {
    m_backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
      [application endBackgroundTask:self->m_backgroundTask];
      self->m_backgroundTask = UIBackgroundTaskInvalid;
    }];
  }

  auto tasks = @[[[MWMBackgroundEditsUpload alloc] init], [[MWMBackgroundUGCUpload alloc] init]];
  [self runBackgroundTasks:tasks completionHandler:nil];

  [MWMRouter saveRouteIfNeeded];
  LOG(LINFO, ("applicationDidEnterBackground - end"));
}

- (void)applicationWillResignActive:(UIApplication *)application
{
  LOG(LINFO, ("applicationWillResignActive - begin"));
  [self.mapViewController onGetFocus:NO];
  auto & f = GetFramework();
  // On some devices we have to free all belong-to-graphics memory
  // because of new OpenGL driver powered by Metal.
  if ([AppInfo sharedInfo].openGLDriver == MWMOpenGLDriverMetalPre103)
  {
    f.SetRenderingDisabled(true);
    f.OnDestroyGLContext();
  }
  else
  {
    f.SetRenderingDisabled(false);
  }
  [MWMLocationManager applicationWillResignActive];
  f.EnterBackground();
  LOG(LINFO, ("applicationWillResignActive - end"));
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
  LOG(LINFO, ("applicationWillEnterForeground - begin"));
  if (!GpsTracker::Instance().IsEnabled())
    return;

  MWMViewController * topVc = static_cast<MWMViewController *>(
      self.mapViewController.navigationController.topViewController);
  if (![topVc isKindOfClass:[MWMViewController class]])
    return;

  if ([MWMSettings isTrackWarningAlertShown])
    return;

  [topVc.alertController presentTrackWarningAlertWithCancelBlock:^{
    GpsTracker::Instance().SetEnabled(false);
  }];

  [MWMSettings setTrackWarningAlertShown:YES];
  LOG(LINFO, ("applicationWillEnterForeground - end"));
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
  LOG(LINFO, ("applicationDidBecomeActive - begin"));
  
  TrackMarketingAppLaunch();
  
  auto & f = GetFramework();
  f.EnterForeground();
  [self.mapViewController onGetFocus:YES];
  [[Statistics instance] applicationDidBecomeActive];
  f.SetRenderingEnabled();
  // On some devices we have to free all belong-to-graphics memory
  // because of new OpenGL driver powered by Metal.
  if ([AppInfo sharedInfo].openGLDriver == MWMOpenGLDriverMetalPre103)
  {
    m2::PointU const size = ((EAGLView *)self.mapViewController.view).pixelSize;
    f.OnRecoverGLContext(static_cast<int>(size.x), static_cast<int>(size.y));
  }
  [MWMLocationManager applicationDidBecomeActive];
  [MWMSearch addCategoriesToSpotlight];
  [MWMKeyboard applicationDidBecomeActive];
  [MWMTextToSpeech applicationDidBecomeActive];
  LOG(LINFO, ("applicationDidBecomeActive - end"));
}

- (BOOL)application:(UIApplication *)application
    continueUserActivity:(NSUserActivity *)userActivity
      restorationHandler:(void (^)(NSArray * restorableObjects))restorationHandler
{
  if ([userActivity.activityType isEqualToString:CSSearchableItemActionType])
  {
    NSString * searchStringKey = userActivity.userInfo[CSSearchableItemActivityIdentifier];
    NSString * searchString = L(searchStringKey);
    if (searchString)
    {
      [self searchText:searchString];
      return YES;
    }
  }
  else if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb])
  {
    auto link = userActivity.webpageURL;
    if ([self checkLaunchURL:[self convertUniversalLink:link]])
    {
      [self handleURLs];
      return YES;
    }
  }

  return NO;
}

- (BOOL)initStatistics:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  Statistics * statistics = [Statistics instance];
  BOOL returnValue =
      [statistics application:application didFinishLaunchingWithOptions:launchOptions];

  NSString * connectionType;
  NSString * network = [Statistics connectionTypeString];
  switch (Platform::ConnectionStatus())
  {
  case Platform::EConnectionType::CONNECTION_NONE: break;
  case Platform::EConnectionType::CONNECTION_WIFI:
    connectionType = @"Wi-Fi";
    break;
  case Platform::EConnectionType::CONNECTION_WWAN:
    connectionType = [[CTTelephonyNetworkInfo alloc] init].currentRadioAccessTechnology;
    break;
  }
  if (!connectionType)
    connectionType = @"Offline";
  [Statistics logEvent:kStatDeviceInfo
        withParameters:@{
          kStatCountry : [AppInfo sharedInfo].countryCode,
          kStatConnection : connectionType
        }];

  auto device = UIDevice.currentDevice;
  device.batteryMonitoringEnabled = YES;
  auto charging = kStatUnknown;
  auto const state = device.batteryState;
  if (state == UIDeviceBatteryStateCharging || state == UIDeviceBatteryStateFull)
    charging = kStatOn;
  else if (state == UIDeviceBatteryStateUnplugged)
    charging = kStatOff;

  [Statistics logEvent:kStatApplicationColdStartupInfo
        withParameters:@{
                         kStatBattery : @(UIDevice.currentDevice.batteryLevel * 100),
                         kStatCharging : charging,
                         kStatNetwork : network
                         }];

  return returnValue;
}

- (void)disableDownloadIndicator
{
  --m_activeDownloadsCounter;
  if (m_activeDownloadsCounter <= 0)
  {
    dispatch_async(dispatch_get_main_queue(), ^{
      UIApplication.sharedApplication.networkActivityIndicatorVisible = NO;
    });
    m_activeDownloadsCounter = 0;
    if (UIApplication.sharedApplication.applicationState == UIApplicationStateBackground)
    {
      [UIApplication.sharedApplication endBackgroundTask:m_backgroundTask];
      m_backgroundTask = UIBackgroundTaskInvalid;
    }
  }
}

- (void)enableDownloadIndicator
{
  ++m_activeDownloadsCounter;
  dispatch_async(dispatch_get_main_queue(), ^{
    UIApplication.sharedApplication.networkActivityIndicatorVisible = YES;
  });
}

+ (NSDictionary *)navigationBarTextAttributes
{
  return @{
    NSForegroundColorAttributeName : [UIColor whitePrimaryText],
    NSFontAttributeName : [UIFont regular18]
  };
}

+ (void)customizeAppearanceForNavigationBar:(UINavigationBar *)navigationBar
{
  navigationBar.tintColor = [UIColor primary];
  navigationBar.barTintColor = [UIColor primary];
  navigationBar.titleTextAttributes = [self navigationBarTextAttributes];
  navigationBar.translucent = NO;
  [navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
  navigationBar.shadowImage = [UIImage new];
  auto backImage = [[UIImage imageNamed:@"ic_nav_bar_back_sys"]
                    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  navigationBar.backIndicatorImage = backImage;
  navigationBar.backIndicatorTransitionMaskImage = backImage;
}

+ (void)customizeAppearance
{
  [UIButton appearance].exclusiveTouch = YES;

  [self customizeAppearanceForNavigationBar:[UINavigationBar appearance]];

  UIBarButtonItem * barBtn = [UIBarButtonItem appearance];
  [barBtn setTitleTextAttributes:[self navigationBarTextAttributes] forState:UIControlStateNormal];
  [barBtn setTitleTextAttributes:@{
    NSForegroundColorAttributeName : [UIColor lightGrayColor],
  }
                        forState:UIControlStateDisabled];
  [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UINavigationBar class]]].tintColor = [UIColor whitePrimaryText];

  UIPageControl * pageControl = [UIPageControl appearance];
  pageControl.pageIndicatorTintColor = [UIColor blackHintText];
  pageControl.currentPageIndicatorTintColor = [UIColor blackSecondaryText];
  pageControl.backgroundColor = [UIColor white];

  UITextField * textField = [UITextField appearance];
  textField.keyboardAppearance =
      [UIColor isNightMode] ? UIKeyboardAppearanceDark : UIKeyboardAppearanceDefault;

  UISearchBar * searchBar = [UISearchBar appearance];
  searchBar.barTintColor = [UIColor primary];
  UITextField * textFieldInSearchBar =
      [UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]];

  textField.backgroundColor = [UIColor white];
  textFieldInSearchBar.defaultTextAttributes = @{
    NSForegroundColorAttributeName : [UIColor blackPrimaryText],
    NSFontAttributeName : [UIFont regular14]
  };
}

- (void)application:(UIApplication *)application
    didReceiveLocalNotification:(UILocalNotification *)notification
{
  [[LocalNotificationManager sharedManager] processNotification:notification onLaunch:NO];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  m_sourceApplication = options[UIApplicationOpenURLOptionsSourceApplicationKey];

  if ([self checkLaunchURL:url])
  {
    [self handleURLs];
    return YES;
  }

  BOOL isGoogleURL = [[GIDSignIn sharedInstance] handleURL:url
                                         sourceApplication:m_sourceApplication
                                                annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
  if (isGoogleURL)
    return YES;

  return [[FBSDKApplicationDelegate sharedInstance] application:app openURL:url options:options];
}

- (BOOL)checkLaunchURL:(NSURL *)url
{
  NSString * scheme = url.scheme;
  m_scheme = scheme;
  if ([scheme isEqualToString:@"geo"] || [scheme isEqualToString:@"ge0"])
  {
    m_geoURL = [url absoluteString];
    return YES;
  }
  else if ([scheme isEqualToString:@"mapswithme"] || [scheme isEqualToString:@"mwm"] ||
           [scheme isEqualToString:@"mapsme"])
  {
    m_mwmURL = [url absoluteString];
    return YES;
  }
  else if ([scheme isEqualToString:@"file"])
  {
    m_fileURL = [url relativePath];
    return YES;
  }
  NSLog(@"Scheme %@ is not supported", scheme);
  return NO;
}

- (void)showMap
{
  [(UINavigationController *)self.window.rootViewController popToRootViewControllerAnimated:YES];
}

- (void)updateApplicationIconBadgeNumber
{
  auto const number = [self badgeNumber];
  UIApplication.sharedApplication.applicationIconBadgeNumber = number;
  [[MWMBottomMenuViewController controller] updateBadgeVisible:number != 0];
}

- (NSUInteger)badgeNumber
{
  auto & s = GetFramework().GetStorage();
  storage::Storage::UpdateInfo updateInfo{};
  s.GetUpdateInfo(s.GetRootId(), updateInfo);
  return updateInfo.m_numberOfMwmFilesToUpdate + (platform::migrate::NeedMigrate() ? 1 : 0);
}

#pragma mark - MWMFrameworkStorageObserver

- (void)processCountryEvent:(storage::TCountryId const &)countryId
{
  // Dispatch this method after delay since there are too many events for group mwms download.
  // We do not need to update badge frequently.
  // Update after 1 second delay (after last country event) is sure enough for app badge.
  SEL const updateBadge = @selector(updateApplicationIconBadgeNumber);
  [NSObject cancelPreviousPerformRequestsWithTarget:self selector:updateBadge object:nil];
  [self performSelector:updateBadge withObject:nil afterDelay:1.0];
}

#pragma mark - Properties

- (MapViewController *)mapViewController
{
  return [(UINavigationController *)self.window.rootViewController viewControllers].firstObject;
}

#pragma mark - TTS

- (void)enableTTSForTheFirstTime
{
  if (![MWMTextToSpeech savedLanguage].length)
    [MWMTextToSpeech setTTSEnabled:YES];
}

#pragma mark - Standby

- (void)enableStandby { self.standbyCounter--; }
- (void)disableStandby { self.standbyCounter++; }
- (void)setStandbyCounter:(NSInteger)standbyCounter
{
  _standbyCounter = MAX(0, standbyCounter);
  dispatch_async(dispatch_get_main_queue(), ^{
    [UIApplication sharedApplication].idleTimerDisabled = (self.standbyCounter != 0);
  });
}

#pragma mark - Alert logic

- (void)firstLaunchSetup
{
  [MWMSettings setStatisticsEnabled:YES];
  NSString * currentVersion =
      [NSBundle.mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
  NSUserDefaults * standartDefaults = NSUserDefaults.standardUserDefaults;
  [standartDefaults setObject:currentVersion forKey:kUDFirstVersionKey];
  [standartDefaults setInteger:1 forKey:kUDSessionsCountKey];
  [standartDefaults setObject:NSDate.date forKey:kUDLastLaunchDateKey];
  [standartDefaults synchronize];
  
  GetPlatform().GetMarketingService().ProcessFirstLaunch();
}

- (void)incrementSessionCount
{
  NSUserDefaults * standartDefaults = NSUserDefaults.standardUserDefaults;
  NSUInteger sessionCount = [standartDefaults integerForKey:kUDSessionsCountKey];
  NSUInteger const kMaximumSessionCountForShowingShareAlert = 50;
  if (sessionCount > kMaximumSessionCountForShowingShareAlert)
    return;

  NSDate * lastLaunchDate = [standartDefaults objectForKey:kUDLastLaunchDateKey];
  NSUInteger daysFromLastLaunch = [self.class daysBetweenNowAndDate:lastLaunchDate];
  if (daysFromLastLaunch > 0)
  {
    sessionCount++;
    [standartDefaults setInteger:sessionCount forKey:kUDSessionsCountKey];
    [standartDefaults setObject:NSDate.date forKey:kUDLastLaunchDateKey];
    [standartDefaults synchronize];
  }
}

- (void)showAlertIfRequired
{
  if ([self shouldShowRateAlert])
  {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showRateAlert) object:nil];
    [self performSelector:@selector(showRateAlert) withObject:nil afterDelay:30.0];
  }
  else if ([self shouldShowFacebookAlert])
  {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showFacebookAlert) object:nil];
    [self performSelector:@selector(showFacebookAlert) withObject:nil afterDelay:30.0];
  }
}

- (void)showAlert:(BOOL)isRate
{
  if (!Platform::IsConnected() || [MWMRouter isRoutingActive])
    return;

  if (isRate)
    [[MWMAlertViewController activeAlertController] presentRateAlert];
  else
    [[MWMAlertViewController activeAlertController] presentFacebookAlert];
  [NSUserDefaults.standardUserDefaults
      setObject:NSDate.date
         forKey:isRate ? kUDLastRateRequestDate : kUDLastShareRequstDate];
}

#pragma mark - Facebook

- (void)showFacebookAlert { [self showAlert:NO]; }
- (BOOL)shouldShowFacebookAlert
{
  NSUInteger const kMaximumSessionCountForShowingShareAlert = 50;
  NSUserDefaults const * const standartDefaults = NSUserDefaults.standardUserDefaults;
  if ([standartDefaults boolForKey:kUDAlreadySharedKey])
    return NO;

  NSUInteger const sessionCount = [standartDefaults integerForKey:kUDSessionsCountKey];
  if (sessionCount > kMaximumSessionCountForShowingShareAlert)
    return NO;

  NSDate * const lastShareRequestDate = [standartDefaults objectForKey:kUDLastShareRequstDate];
  NSUInteger const daysFromLastShareRequest =
      [MapsAppDelegate daysBetweenNowAndDate:lastShareRequestDate];
  if (lastShareRequestDate != nil && daysFromLastShareRequest == 0)
    return NO;

  if (sessionCount == 30 || sessionCount == kMaximumSessionCountForShowingShareAlert)
    return YES;

  if (self.userIsNew)
  {
    if (sessionCount == 12)
      return YES;
  }
  else
  {
    if (sessionCount == 5)
      return YES;
  }
  return NO;
}

#pragma mark - Rate

- (void)showRateAlert { [self showAlert:YES]; }
- (BOOL)shouldShowRateAlert
{
  NSUInteger const kMaximumSessionCountForShowingAlert = 21;
  NSUserDefaults const * const standartDefaults = NSUserDefaults.standardUserDefaults;
  if ([standartDefaults boolForKey:kUDAlreadyRatedKey])
    return NO;

  NSUInteger const sessionCount = [standartDefaults integerForKey:kUDSessionsCountKey];
  if (sessionCount > kMaximumSessionCountForShowingAlert)
    return NO;

  NSDate * const lastRateRequestDate = [standartDefaults objectForKey:kUDLastRateRequestDate];
  NSUInteger const daysFromLastRateRequest =
      [MapsAppDelegate daysBetweenNowAndDate:lastRateRequestDate];
  // Do not show more than one alert per day.
  if (lastRateRequestDate != nil && daysFromLastRateRequest == 0)
    return NO;

  if (self.userIsNew)
  {
    // It's new user.
    if (sessionCount == 3 || sessionCount == 10 ||
        sessionCount == kMaximumSessionCountForShowingAlert)
      return YES;
  }
  else
  {
    // User just got updated. Show alert, if it first session or if 90 days spent.
    if (daysFromLastRateRequest >= 90 || daysFromLastRateRequest == 0)
      return YES;
  }
  return NO;
}

- (BOOL)userIsNew
{
  NSString * currentVersion =
      [NSBundle.mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
  NSString * firstVersion = [NSUserDefaults.standardUserDefaults stringForKey:kUDFirstVersionKey];
  if (!firstVersion.length || firstVersionIsLessThanSecond(firstVersion, currentVersion))
    return NO;

  return YES;
}

+ (NSInteger)daysBetweenNowAndDate:(NSDate *)fromDate
{
  if (!fromDate)
    return 0;

  NSDate * now = NSDate.date;
  NSCalendar * calendar = NSCalendar.currentCalendar;
  [calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:fromDate];
  [calendar rangeOfUnit:NSCalendarUnitDay startDate:&now interval:NULL forDate:now];
  NSDateComponents * difference =
      [calendar components:NSCalendarUnitDay fromDate:fromDate toDate:now options:0];
  return difference.day;
}

#pragma mark - Showcase

- (MWMMyTarget *)myTarget
{
  if (!_myTarget)
    _myTarget = [[MWMMyTarget alloc] init];
  return _myTarget;
}

@end