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

RoutingController.java « routing « maps « mapswithme « com « src « android - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: af50e34f3e717f3ffba52d59c9c2c46367fdddcb (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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
package com.mapswithme.maps.routing;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.DimenRes;
import android.support.annotation.IntRange;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.util.Pair;
import android.support.v7.app.AlertDialog;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.mapswithme.maps.Framework;
import com.mapswithme.maps.MwmApplication;
import com.mapswithme.maps.R;
import com.mapswithme.maps.bookmarks.data.FeatureId;
import com.mapswithme.maps.bookmarks.data.MapObject;
import com.mapswithme.maps.downloader.MapManager;
import com.mapswithme.maps.location.LocationHelper;
import com.mapswithme.maps.taxi.TaxiInfo;
import com.mapswithme.maps.taxi.TaxiInfoError;
import com.mapswithme.maps.taxi.TaxiManager;
import com.mapswithme.util.Config;
import com.mapswithme.util.ConnectionState;
import com.mapswithme.util.NetworkPolicy;
import com.mapswithme.util.StringUtils;
import com.mapswithme.util.Utils;
import com.mapswithme.util.concurrency.UiThread;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import com.mapswithme.util.statistics.AlohaHelper;
import com.mapswithme.util.statistics.Statistics;

import java.util.Calendar;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_POINT_ADD;
import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_POINT_REMOVE;

@android.support.annotation.UiThread
public class RoutingController implements TaxiManager.TaxiListener
{
  private static final String TAG = RoutingController.class.getSimpleName();

  private enum State
  {
    NONE,
    PREPARE,
    NAVIGATION
  }

  enum BuildState
  {
    NONE,
    BUILDING,
    BUILT,
    ERROR
  }

  public interface Container
  {
    FragmentActivity getActivity();
    void showSearch();
    void showRoutePlan(boolean show, @Nullable Runnable completionListener);
    void showNavigation(boolean show);
    void showDownloader(boolean openDownloaded);
    void updateMenu();
    void onTaxiInfoReceived(@NonNull TaxiInfo info);
    void onTaxiError(@NonNull TaxiManager.ErrorCode code);
    void onNavigationCancelled();
    void onNavigationStarted();
    void onAddedStop();
    void onRemovedStop();
    void onBuiltRoute();

    /**
     * @param progress progress to be displayed.
     * */
    void updateBuildProgress(@IntRange(from = 0, to = 100) int progress, @Framework.RouterType int router);
  }

  private static final int NO_WAITING_POI_PICK = -1;
  private static final RoutingController sInstance = new RoutingController();
  private final Logger mLogger = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.ROUTING);
  @Nullable
  private Container mContainer;

  private BuildState mBuildState = BuildState.NONE;
  private State mState = State.NONE;
  @RoutePointInfo.RouteMarkType
  private int mWaitingPoiPickType = NO_WAITING_POI_PICK;
  private int mLastBuildProgress;
  @Framework.RouterType
  private int mLastRouterType;

  private boolean mHasContainerSavedState;
  private boolean mContainsCachedResult;
  private int mLastResultCode;
  private String[] mLastMissingMaps;
  @Nullable
  private RoutingInfo mCachedRoutingInfo;
  private boolean mTaxiRequestHandled;
  private boolean mTaxiPlanning;
  private boolean mInternetConnected;

  private int mInvalidRoutePointsTransactionId;
  private int mRemovingIntermediatePointsTransactionId;

  @SuppressWarnings("FieldCanBeLocal")
  private final Framework.RoutingListener mRoutingListener = new Framework.RoutingListener()
  {
    @Override
    public void onRoutingEvent(final int resultCode, @Nullable final String[] missingMaps)
    {
      mLogger.d(TAG, "onRoutingEvent(resultCode: " + resultCode + ")");

      UiThread.run(new Runnable()
      {
        @Override
        public void run()
        {
          mLastResultCode = resultCode;
          mLastMissingMaps = missingMaps;
          mContainsCachedResult = true;

          if (mLastResultCode == ResultCodesHelper.NO_ERROR
              || ResultCodesHelper.isMoreMapsNeeded(mLastResultCode))
          {
            mCachedRoutingInfo = Framework.nativeGetRouteFollowingInfo();
            setBuildState(BuildState.BUILT);
            mLastBuildProgress = 100;
            if (mContainer != null)
              mContainer.onBuiltRoute();
          }

          processRoutingEvent();
        }
      });
    }
  };

  @SuppressWarnings("FieldCanBeLocal")
  private final Framework.RoutingProgressListener mRoutingProgressListener = new Framework.RoutingProgressListener()
  {
    @Override
    public void onRouteBuildingProgress(final float progress)
    {
      UiThread.run(new Runnable()
      {
        @Override
        public void run()
        {
          mLastBuildProgress = (int) progress;
          updateProgress();
        }
      });
    }
  };

  @SuppressWarnings("FieldCanBeLocal")
  private final Framework.RoutingRecommendationListener mRoutingRecommendationListener =
      new Framework.RoutingRecommendationListener()
  {
    @Override
    public void onRecommend(@Framework.RouteRecommendationType final int recommendation)
    {
      UiThread.run(new Runnable()
      {
        @Override
        public void run()
        {
          if (recommendation == Framework.ROUTE_REBUILD_AFTER_POINTS_LOADING)
            setStartPoint(LocationHelper.INSTANCE.getMyPosition());
        }
      });
    }
  };

  public static RoutingController get()
  {
    return sInstance;
  }

  private void processRoutingEvent()
  {
    if (!mContainsCachedResult ||
        mContainer == null ||
        mHasContainerSavedState)
      return;

    mContainsCachedResult = false;

    if (mLastResultCode == ResultCodesHelper.NO_ERROR)
    {
      updatePlan();
      return;
    }

    if (mLastResultCode == ResultCodesHelper.CANCELLED)
    {
      setBuildState(BuildState.NONE);
      updatePlan();
      return;
    }

    if (!ResultCodesHelper.isMoreMapsNeeded(mLastResultCode))
    {
      setBuildState(BuildState.ERROR);
      mLastBuildProgress = 0;
      updateProgress();
    }

    RoutingErrorDialogFragment fragment = RoutingErrorDialogFragment.create(mLastResultCode, mLastMissingMaps);
    fragment.show(mContainer.getActivity().getSupportFragmentManager(), RoutingErrorDialogFragment.class.getSimpleName());
  }

  private void setState(State newState)
  {
    mLogger.d(TAG, "[S] State: " + mState + " -> " + newState + ", BuildState: " + mBuildState);
    mState = newState;

    if (mContainer != null)
      mContainer.updateMenu();
  }

  private void setBuildState(BuildState newState)
  {
    mLogger.d(TAG, "[B] State: " + mState + ", BuildState: " + mBuildState + " -> " + newState);
    mBuildState = newState;

    if (mBuildState == BuildState.BUILT && !MapObject.isOfType(MapObject.MY_POSITION, getStartPoint()))
      Framework.nativeDisableFollowing();

    if (mContainer != null)
      mContainer.updateMenu();
  }

  private void updateProgress()
  {
    if (isTaxiPlanning())
      return;

    if (mContainer != null)
      mContainer.updateBuildProgress(mLastBuildProgress, mLastRouterType);
  }

  private void showRoutePlan()
  {
    if (mContainer != null)
      mContainer.showRoutePlan(true, new Runnable()
      {
        @Override
        public void run()
        {
          updatePlan();
        }
      });
  }

  public void attach(@NonNull Container container)
  {
    mContainer = container;
  }

  public void initialize()
  {
    mLastRouterType = Framework.nativeGetLastUsedRouter();
    mInvalidRoutePointsTransactionId = Framework.nativeInvalidRoutePointsTransactionId();
    mRemovingIntermediatePointsTransactionId = mInvalidRoutePointsTransactionId;

    Framework.nativeSetRoutingListener(mRoutingListener);
    Framework.nativeSetRouteProgressListener(mRoutingProgressListener);
    Framework.nativeSetRoutingRecommendationListener(mRoutingRecommendationListener);
    TaxiManager.INSTANCE.setTaxiListener(this);
  }

  public void detach()
  {
    mContainer = null;
  }

  @MainThread
  public void restore()
  {
    mHasContainerSavedState = false;
    if (isPlanning())
      showRoutePlan();

    if (mContainer != null)
    {
      if (isTaxiPlanning())
        mContainer.updateBuildProgress(0, mLastRouterType);

      mContainer.showNavigation(isNavigating());
      mContainer.updateMenu();
    }
    processRoutingEvent();
  }

  public void onSaveState()
  {
    mHasContainerSavedState = true;
  }

  private void build()
  {
    Framework.nativeRemoveRoute();

    mLogger.d(TAG, "build");
    mTaxiRequestHandled = false;
    mLastBuildProgress = 0;
    mInternetConnected = ConnectionState.isConnected();

    if (isTaxiRouterType())
    {
      if (!mInternetConnected)
      {
        completeTaxiRequest();
        return;
      }

      MapObject start = getStartPoint();
      MapObject end = getEndPoint();
      if (start != null && end != null)
        requestTaxiInfo(start, end);
    }

    setBuildState(BuildState.BUILDING);
    updatePlan();

    Statistics.INSTANCE.trackRouteBuild(mLastRouterType, getStartPoint(), getEndPoint());
    org.alohalytics.Statistics.logEvent(AlohaHelper.ROUTING_BUILD,
            new String[]{Statistics.EventParam.FROM, Statistics.getPointType(getStartPoint()),
                         Statistics.EventParam.TO, Statistics.getPointType(getEndPoint())});

    Framework.nativeBuildRoute();
  }

  private void completeTaxiRequest()
  {
    mTaxiRequestHandled = true;
    if (mContainer != null)
    {
      mContainer.updateBuildProgress(100, mLastRouterType);
      mContainer.updateMenu();
    }
  }

  private void showDisclaimer(final MapObject startPoint, final MapObject endPoint,
                              final boolean fromApi)
  {
    if (mContainer == null)
      return;

    StringBuilder builder = new StringBuilder();
    for (int resId : new int[] { R.string.dialog_routing_disclaimer_priority, R.string.dialog_routing_disclaimer_precision,
                                 R.string.dialog_routing_disclaimer_recommendations, R.string.dialog_routing_disclaimer_borders,
                                 R.string.dialog_routing_disclaimer_beware })
      builder.append(MwmApplication.get().getString(resId)).append("\n\n");

    new AlertDialog.Builder(mContainer.getActivity())
        .setTitle(R.string.dialog_routing_disclaimer_title)
        .setMessage(builder.toString())
        .setCancelable(false)
        .setNegativeButton(R.string.decline, null)
        .setPositiveButton(R.string.accept, new DialogInterface.OnClickListener()
        {
          @Override
          public void onClick(DialogInterface dlg, int which)
          {
            Config.acceptRoutingDisclaimer();
            prepare(startPoint, endPoint, fromApi);
          }
        }).show();
  }

  public void restoreRoute()
  {
    if (Framework.nativeHasSavedRoutePoints())
    {
      Framework.nativeLoadRoutePoints();
      prepare(getStartPoint(), getEndPoint());
    }
  }

  public void saveRoute()
  {
    if (isNavigating() || (isPlanning() && isBuilt()))
      Framework.nativeSaveRoutePoints();
  }

  public void deleteSavedRoute()
  {
    Framework.nativeDeleteSavedRoutePoints();
  }

  public void prepare(boolean canUseMyPositionAsStart, @Nullable MapObject endPoint)
  {
    prepare(canUseMyPositionAsStart, endPoint, false);
  }

  public void prepare(boolean canUseMyPositionAsStart, @Nullable MapObject endPoint, boolean fromApi)
  {
    MapObject startPoint = canUseMyPositionAsStart ? LocationHelper.INSTANCE.getMyPosition() : null;
    prepare(startPoint, endPoint, fromApi);
  }

  public void prepare(@Nullable MapObject startPoint, @Nullable MapObject endPoint)
  {
    prepare(startPoint, endPoint, false);
  }

  public void prepare(@Nullable MapObject startPoint, @Nullable MapObject endPoint, boolean fromApi)
  {
    mLogger.d(TAG, "prepare (" + (endPoint == null ? "route)" : "p2p)"));

    if (!Config.isRoutingDisclaimerAccepted())
    {
      showDisclaimer(startPoint, endPoint, fromApi);
      return;
    }

    if (startPoint != null && endPoint != null)
      mLastRouterType = Framework.nativeGetBestRouter(startPoint.getLat(), startPoint.getLon(),
                                                      endPoint.getLat(), endPoint.getLon());
    prepare(startPoint, endPoint, mLastRouterType, fromApi);
  }

  public void prepare(final @Nullable MapObject startPoint, final @Nullable MapObject endPoint,
                      @Framework.RouterType int routerType)
  {
    prepare(startPoint, endPoint, routerType, false);
  }

  public void prepare(final @Nullable MapObject startPoint, final @Nullable MapObject endPoint,
                      @Framework.RouterType int routerType, boolean fromApi)
  {
    cancel();
    setState(State.PREPARE);

    mLastRouterType = routerType;
    Framework.nativeSetRouter(mLastRouterType);

    if (startPoint != null || endPoint != null)
      setPointsInternal(startPoint, endPoint);

    if (mContainer != null)
      mContainer.showRoutePlan(true, new Runnable()
      {
        @Override
        public void run()
        {
          if (startPoint == null || endPoint == null)
            updatePlan();
          else
            build();
        }
      });

    if (startPoint != null)
      trackPointAdd(startPoint, RoutePointInfo.ROUTE_MARK_START, false, false, fromApi);
    if (endPoint != null)
      trackPointAdd(endPoint, RoutePointInfo.ROUTE_MARK_FINISH, false, false, fromApi);
  }

  private static void trackPointAdd(@NonNull MapObject point, @RoutePointInfo.RouteMarkType int type,
                          boolean isPlanning, boolean isNavigating, boolean fromApi)
  {
    boolean isMyPosition = point.getMapObjectType() == MapObject.MY_POSITION;
    Statistics.INSTANCE.trackRoutingPoint(ROUTING_POINT_ADD, type, isPlanning, isNavigating,
                                          isMyPosition, fromApi);
  }

  private static void trackPointRemove(@NonNull MapObject point, @RoutePointInfo.RouteMarkType int type,
                             boolean isPlanning, boolean isNavigating, boolean fromApi)
  {
    boolean isMyPosition = point.getMapObjectType() == MapObject.MY_POSITION;
    Statistics.INSTANCE.trackRoutingPoint(ROUTING_POINT_REMOVE, type, isPlanning, isNavigating,
                                          isMyPosition, fromApi);
  }

  public void start()
  {
    mLogger.d(TAG, "start");


    MapObject my = LocationHelper.INSTANCE.getMyPosition();

    if (my == null || !MapObject.isOfType(MapObject.MY_POSITION, getStartPoint()))
    {
      Statistics.INSTANCE.trackEvent(Statistics.EventName.ROUTING_START_SUGGEST_REBUILD);
      AlohaHelper.logClick(AlohaHelper.ROUTING_START_SUGGEST_REBUILD);
      suggestRebuildRoute();
      return;
    }

    Statistics.INSTANCE.trackEvent(Statistics.EventName.ROUTING_START);
    AlohaHelper.logClick(AlohaHelper.ROUTING_START);
    setState(State.NAVIGATION);

    if (mContainer != null)
    {
      mContainer.showRoutePlan(false, null);
      mContainer.showNavigation(true);
      mContainer.onNavigationStarted();
    }

    Framework.nativeFollowRoute();
    LocationHelper.INSTANCE.restart();
  }

  public void addStop(@NonNull MapObject mapObject)
  {
    addRoutePoint(RoutePointInfo.ROUTE_MARK_INTERMEDIATE, mapObject);
    build();
    if (mContainer != null)
      mContainer.onAddedStop();
    backToPlaningStateIfNavigating();
    trackPointAdd(mapObject, RoutePointInfo.ROUTE_MARK_INTERMEDIATE, isPlanning(), isNavigating(),
                  false);
  }

  public void removeStop(@NonNull MapObject mapObject)
  {
    RoutePointInfo info = mapObject.getRoutePointInfo();
    if (info == null)
      throw new AssertionError("A stop point must have the route point info!");

    applyRemovingIntermediatePointsTransaction();
    Framework.nativeRemoveRoutePoint(info.mMarkType, info.mIntermediateIndex);
    build();
    if (mContainer != null)
      mContainer.onRemovedStop();
    backToPlaningStateIfNavigating();
    trackPointRemove(mapObject, info.mMarkType, isPlanning(), isNavigating(), false);
  }

  private void backToPlaningStateIfNavigating()
  {
    if (!isNavigating())
      return;

    setState(State.PREPARE);
    if (mContainer != null)
    {
      mContainer.showNavigation(false);
      mContainer.showRoutePlan(true, null);
      mContainer.updateMenu();
      mContainer.onNavigationCancelled();
    }
  }

  private void removeIntermediatePoints()
  {
    Framework.nativeRemoveIntermediateRoutePoints();
  }

  @NonNull
  private MapObject toMapObject(@NonNull RouteMarkData point)
  {
    return MapObject.createMapObject(FeatureId.EMPTY, point.mIsMyPosition ? MapObject.MY_POSITION : MapObject.POI,
                         point.mTitle == null ? "" : point.mTitle,
                         point.mSubtitle == null ? "" : point.mSubtitle, point.mLat, point.mLon);
  }

  public boolean isStopPointAllowed()
  {
    return Framework.nativeCouldAddIntermediatePoint() && !isTaxiRouterType();
  }

  public boolean isRoutePoint(@NonNull MapObject mapObject)
  {
    return mapObject.getRoutePointInfo() != null;
  }

  private void suggestRebuildRoute()
  {
    if (mContainer == null)
      return;

    final AlertDialog.Builder builder = new AlertDialog.Builder(mContainer.getActivity())
                                                       .setMessage(R.string.p2p_reroute_from_current)
                                                       .setCancelable(false)
                                                       .setNegativeButton(R.string.cancel, null);

    TextView titleView = (TextView)View.inflate(mContainer.getActivity(), R.layout.dialog_suggest_reroute_title, null);
    titleView.setText(R.string.p2p_only_from_current);
    builder.setCustomTitle(titleView);

    if (MapObject.isOfType(MapObject.MY_POSITION, getEndPoint()))
    {
      builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
      {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
          swapPoints();
        }
      });
    }
    else
    {
      if (LocationHelper.INSTANCE.getMyPosition() == null)
        builder.setMessage(null).setNegativeButton(null, null);

      builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
      {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
          setStartFromMyPosition();
        }
      });
    }

    builder.show();
  }

  private void updatePlan()
  {
    updateProgress();
  }

  private void cancelInternal()
  {
    mLogger.d(TAG, "cancelInternal");

    //noinspection WrongConstant
    mWaitingPoiPickType = NO_WAITING_POI_PICK;
    mTaxiRequestHandled = false;

    setBuildState(BuildState.NONE);
    setState(State.NONE);

    applyRemovingIntermediatePointsTransaction();
    Framework.nativeCloseRouting();
  }

  public boolean cancel()
  {
    if (isPlanning())
    {
      mLogger.d(TAG, "cancel: planning");

      cancelInternal();
      if (mContainer != null)
        mContainer.showRoutePlan(false, null);
      return true;
    }

    if (isNavigating())
    {
      mLogger.d(TAG, "cancel: navigating");

      cancelInternal();
      if (mContainer != null)
      {
        mContainer.showNavigation(false);
        mContainer.updateMenu();
      }
      if (mContainer != null)
        mContainer.onNavigationCancelled();
      return true;
    }

    mLogger.d(TAG, "cancel: none");
    return false;
  }

  public boolean isPlanning()
  {
    return mState == State.PREPARE;
  }

  boolean isTaxiPlanning()
  {
    return isTaxiRouterType() && mTaxiPlanning;
  }

  boolean isTaxiRouterType()
  {
    return mLastRouterType == Framework.ROUTER_TYPE_TAXI;
  }

  boolean isVehicleRouterType()
  {
    return mLastRouterType == Framework.ROUTER_TYPE_VEHICLE;
  }

  public boolean isNavigating()
  {
    return mState == State.NAVIGATION;
  }

  public boolean isVehicleNavigation()
  {
    return isNavigating() && isVehicleRouterType();
  }

  public boolean isBuilding()
  {
    return mState == State.PREPARE && mBuildState == BuildState.BUILDING;
  }

  public boolean isErrorEncountered()
  {
    return mBuildState == BuildState.ERROR;
  }

  public boolean isBuilt()
  {
    return mBuildState == BuildState.BUILT;
  }

  public void waitForPoiPick(@RoutePointInfo.RouteMarkType int pointType){
    mWaitingPoiPickType = pointType;
  }

  public boolean isWaitingPoiPick()
  {
    return mWaitingPoiPickType != NO_WAITING_POI_PICK;
  }

  public boolean isTaxiRequestHandled()
  {
    return mTaxiRequestHandled;
  }

  boolean isInternetConnected()
  {
    return mInternetConnected;
  }

  BuildState getBuildState()
  {
    return mBuildState;
  }

  @Nullable
  MapObject getStartPoint()
  {
    return getStartOrEndPointByType(RoutePointInfo.ROUTE_MARK_START);
  }

  @Nullable
  MapObject getEndPoint()
  {
    return getStartOrEndPointByType(RoutePointInfo.ROUTE_MARK_FINISH);
  }

  @Nullable
  private MapObject getStartOrEndPointByType(@RoutePointInfo.RouteMarkType int type)
  {
    RouteMarkData[] points = Framework.nativeGetRoutePoints();
    int size = points.length;

    if (size == 0)
      return null;

    if (size == 1)
    {
      RouteMarkData point = points[0];
      return point.mPointType == type ? toMapObject(point) : null;
    }

    if (type == RoutePointInfo.ROUTE_MARK_START)
      return toMapObject(points[0]);
    if (type == RoutePointInfo.ROUTE_MARK_FINISH)
      return toMapObject(points[size - 1]);

    return null;
  }

  public boolean hasStartPoint()
  {
    return getStartPoint() != null;
  }

  public boolean hasEndPoint()
  {
    return getEndPoint() != null;
  }

  @Nullable
  RoutingInfo getCachedRoutingInfo()
  {
    return mCachedRoutingInfo;
  }

  private void setPointsInternal(@Nullable MapObject startPoint, @Nullable MapObject endPoint)
  {
    if (startPoint != null)
    {
      applyRemovingIntermediatePointsTransaction();
      addRoutePoint(RoutePointInfo.ROUTE_MARK_START, startPoint);
      if (mContainer != null)
        mContainer.updateMenu();
    }

    if (endPoint != null)
    {
      applyRemovingIntermediatePointsTransaction();
      addRoutePoint(RoutePointInfo.ROUTE_MARK_FINISH, endPoint);
      if (mContainer != null)
        mContainer.updateMenu();
    }
  }

  void checkAndBuildRoute()
  {
    if (isWaitingPoiPick())
      showRoutePlan();

    if (getStartPoint() != null && getEndPoint() != null)
      build();
  }

  private boolean setStartFromMyPosition()
  {
    mLogger.d(TAG, "setStartFromMyPosition");

    MapObject my = LocationHelper.INSTANCE.getMyPosition();
    if (my == null)
    {
      mLogger.d(TAG, "setStartFromMyPosition: no my position - skip");
      return false;
    }

    return setStartPoint(my);
  }

  /**
   * Sets starting point.
   * <ul>
   *   <li>If {@code point} matches ending one and the starting point was set &mdash; swap points.
   *   <li>The same as the currently set starting point is skipped.
   * </ul>
   * Route starts to build if both points were set.
   *
   * @return {@code true} if the point was set.
   */
  @SuppressWarnings("Duplicates")
  public boolean setStartPoint(@Nullable MapObject point)
  {
    mLogger.d(TAG, "setStartPoint");
    MapObject startPoint = getStartPoint();
    MapObject endPoint = getEndPoint();
    boolean isSamePoint = MapObject.same(startPoint, point);
    if (point != null)
    {
      applyRemovingIntermediatePointsTransaction();
      addRoutePoint(RoutePointInfo.ROUTE_MARK_START, point);
      startPoint = getStartPoint();
    }

    if (isSamePoint)
    {
      mLogger.d(TAG, "setStartPoint: skip the same starting point");
      return false;
    }

    if (point != null && point.sameAs(endPoint))
    {
      if (startPoint == null)
      {
        mLogger.d(TAG, "setStartPoint: skip because starting point is empty");
        return false;
      }

      mLogger.d(TAG, "setStartPoint: swap with end point");
      endPoint = startPoint;
    }

    startPoint = point;
    setPointsInternal(startPoint, endPoint);
    checkAndBuildRoute();
    if (startPoint != null)
      trackPointAdd(startPoint, RoutePointInfo.ROUTE_MARK_START, isPlanning(), isNavigating(),
                    false);
    return true;
  }

  /**
   * Sets ending point.
   * <ul>
   *   <li>If {@code point} is the same as starting point &mdash; swap points if ending point is set, skip otherwise.
   *   <li>Set starting point to MyPosition if it was not set before.
   * </ul>
   * Route starts to build if both points were set.
   *
   * @return {@code true} if the point was set.
   */
  @SuppressWarnings("Duplicates")
  public boolean setEndPoint(@Nullable MapObject point)
  {
    mLogger.d(TAG, "setEndPoint");
    MapObject startPoint = getStartPoint();
    MapObject endPoint = getEndPoint();
    boolean isSamePoint = MapObject.same(endPoint, point);
    if (point != null)
    {
      applyRemovingIntermediatePointsTransaction();

      addRoutePoint(RoutePointInfo.ROUTE_MARK_FINISH, point);
      endPoint = getEndPoint();
    }

    if (isSamePoint)
    {
      mLogger.d(TAG, "setEndPoint: skip the same end point");
      return false;
    }

    if (point != null && point.sameAs(startPoint))
    {
      if (endPoint == null)
      {
        mLogger.d(TAG, "setEndPoint: skip because end point is empty");
        return false;
      }

      mLogger.d(TAG, "setEndPoint: swap with starting point");
      startPoint = endPoint;

    }

    endPoint = point;

    if (endPoint != null)
      trackPointAdd(endPoint, RoutePointInfo.ROUTE_MARK_FINISH, isPlanning(), isNavigating(),
                    false);

    setPointsInternal(startPoint, endPoint);
    checkAndBuildRoute();
    return true;
  }

  private static void addRoutePoint(@RoutePointInfo.RouteMarkType int type, @NonNull MapObject point)
  {
    Pair<String, String> description = getDescriptionForPoint(point);
    Framework.nativeAddRoutePoint(description.first /* title */, description.second /* subtitle */,
                                  type, 0 /* intermediateIndex */,
                                  MapObject.isOfType(MapObject.MY_POSITION, point),
                                  point.getLat(), point.getLon());
  }

  @NonNull
  private static Pair<String, String> getDescriptionForPoint(@NonNull MapObject point)
  {
    String title, subtitle = "";
    if (!TextUtils.isEmpty(point.getTitle()))
    {
      title = point.getTitle();
      subtitle = point.getSubtitle();
    }
    else
    {
      if (!TextUtils.isEmpty(point.getSubtitle()))
      {
        title = point.getSubtitle();
      }
      else if (!TextUtils.isEmpty(point.getAddress()))
      {
        title = point.getAddress();
      }
      else
      {
        title = Framework.nativeFormatLatLon(point.getLat(), point.getLon(), false /* useDmsFormat */);
      }
    }
    return new Pair<>(title, subtitle);
  }

  private void swapPoints()
  {
    mLogger.d(TAG, "swapPoints");

    MapObject startPoint = getStartPoint();
    MapObject endPoint = getEndPoint();
    MapObject point = startPoint;
    startPoint = endPoint;
    endPoint = point;

    Statistics.INSTANCE.trackEvent(Statistics.EventName.ROUTING_SWAP_POINTS);
    AlohaHelper.logClick(AlohaHelper.ROUTING_SWAP_POINTS);

    setPointsInternal(startPoint, endPoint);
    checkAndBuildRoute();
    if (mContainer != null)
      mContainer.updateMenu();
  }

  public void setRouterType(@Framework.RouterType int router)
  {
    mLogger.d(TAG, "setRouterType: " + mLastRouterType + " -> " + router);

    // Repeating tap on Taxi icon should trigger the route building always,
    // because it may be "No internet connection, try later" case
    if (router == mLastRouterType && !isTaxiRouterType())
      return;

    mLastRouterType = router;
    Framework.nativeSetRouter(router);

    // Taxi routing does not support intermediate points.
    if (isTaxiRouterType())
    {
      openRemovingIntermediatePointsTransaction();
      removeIntermediatePoints();
    }
    else
    {
      cancelRemovingIntermediatePointsTransaction();
    }

    if (getStartPoint() != null && getEndPoint() != null)
      build();
  }

  private void openRemovingIntermediatePointsTransaction()
  {
    if (mRemovingIntermediatePointsTransactionId == mInvalidRoutePointsTransactionId)
      mRemovingIntermediatePointsTransactionId = Framework.nativeOpenRoutePointsTransaction();
  }

  private void cancelRemovingIntermediatePointsTransaction()
  {
    if (mRemovingIntermediatePointsTransactionId == mInvalidRoutePointsTransactionId)
      return;
    Framework.nativeCancelRoutePointsTransaction(mRemovingIntermediatePointsTransactionId);
    mRemovingIntermediatePointsTransactionId = mInvalidRoutePointsTransactionId;
  }

  private void applyRemovingIntermediatePointsTransaction()
  {
    // We have to apply removing intermediate points transaction each time
    // we add/remove route points in the taxi mode.
    if (mRemovingIntermediatePointsTransactionId == mInvalidRoutePointsTransactionId)
      return;
    Framework.nativeApplyRoutePointsTransaction(mRemovingIntermediatePointsTransactionId);
    mRemovingIntermediatePointsTransactionId = mInvalidRoutePointsTransactionId;
  }

  public void onPoiSelected(@Nullable MapObject point)
  {
    if (!isWaitingPoiPick())
      return;

    if (mWaitingPoiPickType != RoutePointInfo.ROUTE_MARK_FINISH
        && mWaitingPoiPickType != RoutePointInfo.ROUTE_MARK_START)
    {
      throw new AssertionError("Only start and finish points can be added through search!");
    }

    if (point != null)
    {
      if (mWaitingPoiPickType == RoutePointInfo.ROUTE_MARK_FINISH)
        setEndPoint(point);
      else
        setStartPoint(point);
    }

    if (mContainer != null)
    {
      mContainer.updateMenu();
      showRoutePlan();
    }

    //noinspection WrongConstant
    mWaitingPoiPickType = NO_WAITING_POI_PICK;
  }

  public static CharSequence formatRoutingTime(Context context, int seconds, @DimenRes int unitsSize)
  {
    long minutes = TimeUnit.SECONDS.toMinutes(seconds) % 60;
    long hours = TimeUnit.SECONDS.toHours(seconds);
    String min = context.getString(R.string.minute);
    String hour = context.getString(R.string.hour);
    @DimenRes
    int textSize = R.dimen.text_size_routing_number;
    SpannableStringBuilder displayedH = Utils.formatUnitsText(context, textSize, unitsSize,
                                                              String.valueOf(hours), hour);
    SpannableStringBuilder displayedM = Utils.formatUnitsText(context, textSize, unitsSize,
                                                              String.valueOf(minutes), min);
    return hours == 0 ? displayedM : TextUtils.concat(displayedH + " ", displayedM);
  }

  static String formatArrivalTime(int seconds)
  {
    Calendar current = Calendar.getInstance();
    current.set(Calendar.SECOND, 0);
    current.add(Calendar.SECOND, seconds);
    return StringUtils.formatUsingUsLocale("%d:%02d", current.get(Calendar.HOUR_OF_DAY), current.get(Calendar.MINUTE));
  }

  public boolean checkMigration(Activity activity)
  {
    if (!MapManager.nativeIsLegacyMode())
      return false;

    if (!isNavigating() && !isPlanning())
      return false;

    new AlertDialog.Builder(activity)
        .setTitle(R.string.migrate_title)
        .setMessage(R.string.no_migration_during_navigation)
        .setPositiveButton(android.R.string.ok, null)
        .show();

    return true;
  }

  private void requestTaxiInfo(@NonNull MapObject startPoint, @NonNull MapObject endPoint)
  {
    mTaxiPlanning = true;

    TaxiManager.INSTANCE.nativeRequestTaxiProducts(NetworkPolicy.newInstance(true /* canUse */),
                                   startPoint.getLat(), startPoint.getLon(),
                                   endPoint.getLat(), endPoint.getLon());
    if (mContainer != null)
      mContainer.updateBuildProgress(0, mLastRouterType);
  }

  @Override
  public void onTaxiProviderReceived(@NonNull TaxiInfo provider)
  {
    mTaxiPlanning = false;
    mLogger.d(TAG, "onTaxiInfoReceived provider = " + provider);
    if (isTaxiRouterType() && mContainer != null)
    {
      mContainer.onTaxiInfoReceived(provider);
      completeTaxiRequest();
      Statistics.INSTANCE.trackTaxiEvent(Statistics.EventName.ROUTING_TAXI_ROUTE_BUILT,
                                         provider.getType());
    }
  }

  @Override
  public void onTaxiErrorReceived(@NonNull TaxiInfoError error)
  {
    mTaxiPlanning = false;
    mLogger.e(TAG, "onTaxiError error = " + error);
    if (isTaxiRouterType() && mContainer != null)
    {
      mContainer.onTaxiError(error.getCode());
      completeTaxiRequest();
      Statistics.INSTANCE.trackTaxiError(error);
    }
  }

  @Override
  public void onNoTaxiProviders()
  {
    mTaxiPlanning = false;
    mLogger.e(TAG, "onNoTaxiProviders");
    if (isTaxiRouterType() && mContainer != null)
    {
      mContainer.onTaxiError(TaxiManager.ErrorCode.NoProviders);
      completeTaxiRequest();
      Statistics.INSTANCE.trackNoTaxiProvidersError();
    }
  }
}