aboutsummaryrefslogtreecommitdiffhomepage
path: root/Example/Auth/Sample/MainViewController.m
blob: eb4522688fffa4a388e592954cc22ec6fc6e91d9 (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
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
/*
 * Copyright 2017 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "MainViewController.h"

#import <objc/runtime.h>

#import "AppManager.h"
#import "AuthCredentials.h"
#import "FIRAdditionalUserInfo.h"
#import "FirebaseCommunity/FIRApp.h"
#import "FirebaseCommunity/FIRAppInternal.h"
#import "FirebaseCommunity/FIRAppAssociationRegistration.h"
#import "FIROAuthProvider.h"
#import "FIRPhoneAuthCredential.h"
#import "FIRPhoneAuthProvider.h"
#import "FirebaseAuth.h"
#import "CustomTokenDataEntryViewController.h"
#import "FacebookAuthProvider.h"
#import "GoogleAuthProvider.h"
#import "SettingsViewController.h"
#import "StaticContentTableViewManager.h"
#import "UIViewController+Alerts.h"
#import "UserInfoViewController.h"
#import "UserTableViewCell.h"


/*! @typedef textInputCompletionBlock
    @brief The type of callback used to report text input prompt results.
 */
typedef void (^textInputCompletionBlock)(NSString *_Nullable userInput);

/** @var kTokenGetButtonText
    @brief The text of the "Get Token" button.
 */
static NSString *const kTokenGetButtonText = @"Get Token";

/** @var kTokenRefreshButtonText
    @brief The text of the "Refresh Token" button.
 */
static NSString *const kTokenRefreshButtonText = @"Force Refresh Token";

/** @var kTokenRefreshedAlertTitle
    @brief The title of the "Token Refreshed" alert.
 */
static NSString *const kTokenRefreshedAlertTitle = @"Token";

/** @var kTokenRefreshErrorAlertTitle
    @brief The title of the "Token Refresh error" alert.
 */
static NSString *const kTokenRefreshErrorAlertTitle = @"Get Token Error";

/** @var kSettingsButtonTextDesription
    @brief The description for the text of the "Settings" button.
 */
static NSString *const kSettingsButtonTextDesription =
    @"The button text to open sample app settings";

/** @var kUserInfoButtonText
    @brief The text of the "Show User Info" button.
 */
static NSString *const kUserInfoButtonText = @"[Show User Info]";

/** @var kSetImageURLText
    @brief The text of the "Set Photo url" button.
 */
static NSString *const kSetPhotoURLText = @"Set Photo url";

/** @var kSignInGoogleButtonText
    @brief The text of the "Google SignIn" button.
 */
static NSString *const kSignInGoogleButtonText = @"Sign in with Google";

/** @var kSignInAndRetrieveGoogleButtonText
    @brief The text of the "Sign in with Google and retrieve data" button.
 */
static NSString *const kSignInGoogleAndRetrieveDataButtonText =
    @"Sign in with Google and retrieve data";

/** @var kSignInFacebookButtonText
    @brief The text of the "Facebook SignIn" button.
 */
static NSString *const kSignInFacebookButtonText = @"Sign in with Facebook";

/** @var kSignInFacebookAndRetrieveDataButtonText
    @brief The text of the "Facebook SignIn and retrieve data" button.
 */
static NSString *const kSignInFacebookAndRetrieveDataButtonText =
    @"Sign in with Facebook and retrieve data";

/** @var kSignInEmailPasswordButtonText
    @brief The text of the "Email/Password SignIn" button.
 */
static NSString *const kSignInEmailPasswordButtonText = @"Sign in with Email/Password";

/** @var kSignInWithCustomTokenButtonText
    @brief The text of the "Sign In (BYOAuth)" button.
 */
static NSString *const kSignInWithCustomTokenButtonText = @"Sign In (BYOAuth)";

/** @var kSignInAnonymouslyButtonText
    @brief The text of the "Sign In Anonymously" button.
 */
static NSString *const kSignInAnonymouslyButtonText = @"Sign In Anonymously";

/** @var kSignInAnonymouslyWithAuthResultButtonText
    @brief The text of the "Sign In Anonymously (AuthDataResult)" button.
 */
static NSString *const kSignInAnonymouslyWithAuthResultButtonText =
    @"Sign In Anonymously (AuthDataResult)";

/** @var kSignedInAlertTitle
    @brief The text of the "Sign In Succeeded" alert.
 */
static NSString *const kSignedInAlertTitle = @"Signed In";

/** @var kSignInErrorAlertTitle
    @brief The text of the "Sign In Encountered an Error" alert.
 */
static NSString *const kSignInErrorAlertTitle = @"Sign-In Error";

/** @var kSignOutButtonText
    @brief The text of the "Sign Out" button.
 */
static NSString *const kSignOutButtonText = @"Sign Out";

/** @var kDeleteAccountText
    @brief The text of the "Delete Account" button.
 */
static NSString *const kDeleteUserText = @"Delete Account";

/** @var kReauthenticateGoogleText
    @brief The text of the "Reathenticate Google" button.
 */
static NSString *const kReauthenticateGoogleText = @"Reauthenticate Google";

/** @var kReauthenticateGoogleAndRetrieveDataText
    @brief The text of the "Reathenticate Google and retrieve data" button.
 */
static NSString *const kReauthenticateGoogleAndRetrieveDataText =
    @"Reauthenticate Google and retrieve data";

/** @var kReauthenticateFBText
    @brief The text of the "Reathenticate Facebook" button.
 */
static NSString *const kReauthenticateFBText = @"Reauthenticate FB";

/** @var kReauthenticateFBAndRetrieveDataText
    @brief The text of the "Reathenticate Facebook and retrieve data" button.
 */
static NSString *const kReauthenticateFBAndRetrieveDataText =
    @"Reauthenticate FB and retrieve data";

/** @var kReAuthenticateEmail
    @brief The text of the "Reathenticate Email" button.
 */
static NSString *const kReauthenticateEmailText = @"Reauthenticate Email/Password";

/** @var kOKButtonText
    @brief The text of the "OK" button for the Sign In result dialogs.
 */
static NSString *const kOKButtonText = @"OK";

/** @var kSetDisplayNameTitle
    @brief The title of the "Set Display Name" error dialog.
 */
static NSString *const kSetDisplayNameTitle = @"Set Display Name";

/** @var kUpdateEmailText
    @brief The title of the "Update Email" button.
 */
static NSString *const kUpdateEmailText = @"Update Email";

/** @var kUpdatePasswordText
    @brief The title of the "Update Password" button.
 */
static NSString *const kUpdatePasswordText = @"Update Password";

/** @var kUpdatePhoneNumber
    @brief The title of the "Update Photo" button.
 */
static NSString *const kUpdatePhoneNumber = @"Update Phone Number";

/** @var kLinkPhoneNumber
    @brief The title of the "Link phone" button.
 */
static NSString *const kLinkPhoneNumber = @"Link Phone Number";

/** @var kUnlinkPhone
    @brief The title of the "Unlink Phone" button for unlinking phone auth provider.
 */
static NSString *const kUnlinkPhoneNumber = @"Unlink Phone Number";

/** @var kReloadText
    @brief The title of the "Reload User" button.
 */
static NSString *const kReloadText = @"Reload User";

/** @var kLinkWithGoogleText
    @brief The title of the "Link with Google" button.
 */
static NSString *const kLinkWithGoogleText = @"Link with Google";

/** @var kLinkWithGoogleAndRetrieveDataText
    @brief The title of the "Link with Google and retrieve data" button.
 */
static NSString *const kLinkWithGoogleAndRetrieveDataText = @"Link with Google and retrieve data";

/** @var kLinkWithFacebookText
    @brief The title of the "Link with Facebook Account" button.
 */
static NSString *const kLinkWithFacebookText = @"Link with Facebook";

/** @var kLinkWithFacebookAndRetrieveDataText
    @brief The title of the "Link with Facebook and retrieve data" button.
 */
static NSString *const kLinkWithFacebookAndRetrieveDataText =
    @"Link with Facebook and retrieve data";

/** @var kLinkWithEmailPasswordText
    @brief The title of the "Link with Email/Password Account" button.
 */
static NSString *const kLinkWithEmailPasswordText = @"Link with Email/Password";

/** @var kUnlinkTitle
    @brief The text of the "Unlink from Provider" error Dialog.
 */
static NSString *const kUnlinkTitle = @"Unlink from Provider";

/** @var kUnlinkFromGoogle
    @brief The text of the "Unlink from Google" button.
 */
static NSString *const kUnlinkFromGoogle = @"Unlink from Google";

/** @var kUnlinkFromFacebook
    @brief The text of the "Unlink from Facebook" button.
 */
static NSString *const kUnlinkFromFacebook = @"Unlink from Facebook";

/** @var kUnlinkFromEmailPassword
    @brief The text of the "Unlink from Google" button.
 */
static NSString *const kUnlinkFromEmailPassword = @"Unlink from Email/Password";

/** @var kGetProvidersForEmail
    @brief The text of the "Get Provider IDs for Email" button.
 */
static NSString *const kGetProvidersForEmail = @"Get Provider IDs for Email";

/** @var kActionCodeTypeDescription
    @brief The description of the "Action Type" entry.
 */
static NSString *const kActionCodeTypeDescription = @"Action Type";

/** @var kContinueURLDescription
    @brief The description of the "Continue URL" entry.
 */
static NSString *const kContinueURLDescription = @"Continue URL";

/** @var kRequestVerifyEmail
    @brief The text of the "Request Verify Email Link" button.
 */
static NSString *const kRequestVerifyEmail = @"Request Verify Email Link";

/** @var kRequestPasswordReset
    @brief The text of the "Email Password Reset" button.
 */
static NSString *const kRequestPasswordReset = @"Send Password Reset Email";

/** @var kResetPassword
    @brief The text of the "Password Reset" button.
 */
static NSString *const kResetPassword = @"Reset Password";

/** @var kCheckActionCode
    @brief The text of the "Check action code" button.
 */
static NSString *const kCheckActionCode = @"Check action code";

/** @var kApplyActionCode
    @brief The text of the "Apply action code" button.
 */
static NSString *const kApplyActionCode = @"Apply action code";

/** @var kVerifyPasswordResetCode
    @brief The text of the "Verify password reset code" button.
 */
static NSString *const kVerifyPasswordResetCode = @"Verify password reset code";

/** @var kSectionTitleSettings
    @brief The text for the title of the "Settings" section.
 */
static NSString *const kSectionTitleSettings = @"SETTINGS";

/** @var kSectionTitleSignIn
    @brief The text for the title of the "Sign-In" section.
 */
static NSString *const kSectionTitleSignIn = @"SIGN-IN";

/** @var kSectionTitleReauthenticate
    @brief The text for the title of the "Reauthenticate" section.
 */
static NSString *const kSectionTitleReauthenticate = @"REAUTHENTICATE";

/** @var kSectionTitleTokenActions
    @brief The text for the title of the "Token Actions" section.
 */
static NSString *const kSectionTitleTokenActions = @"TOKEN ACTIONS";

/** @var kSectionTitleEditUser
    @brief The text for the title of the "Edit User" section.
 */
static NSString *const kSectionTitleEditUser = @"EDIT USER";

/** @var kSectionTitleLinkUnlinkAccount
    @brief The text for the title of the "Link/Unlink account" section.
 */
static NSString *const kSectionTitleLinkUnlinkAccounts = @"LINK/UNLINK ACCOUNT";

/** @var kSectionTitleUserActions
    @brief The text for the title of the "User Actions" section.
 */
static NSString *const kSectionTitleUserActions = @"USER ACTIONS";

/** @var kSectionTitleOOBAction
    @brief The text for the title of the "OOB Actions" section.
 */
static NSString *const kSectionTitleOOBActions = @"OOB ACTIONS";

/** @var kSectionTitleUserDetails
    @brief The text for the title of the "User Details" section.
 */
static NSString *const kSectionTitleUserDetails = @"SIGNED-IN USER DETAILS";

/** @var kSectionTitleListeners
    @brief The title for the table view section dedicated to auth state did change listeners.
 */
static NSString *const kSectionTitleListeners = @"Listeners";

/** @var kAddAuthStateListenerTitle
    @brief The title for the table view row which adds a block to the auth state did change
        listeners.
 */
static NSString *const kAddAuthStateListenerTitle = @"Add Auth State Change Listener";

/** @var kRemoveAuthStateListenerTitle
    @brief The title for the table view row which removes a block to the auth state did change
        listeners.
 */
static NSString *const kRemoveAuthStateListenerTitle = @"Remove Last Auth State Change Listener";

/** @var kAddIDTokenListenerTitle
    @brief The title for the table view row which adds a block to the ID token did change
        listeners.
 */
static NSString *const kAddIDTokenListenerTitle = @"Add ID Token Change Listener";

/** @var kRemoveIDTokenListenerTitle
    @brief The title for the table view row which removes a block to the ID token did change
        listeners.
 */
static NSString *const kRemoveIDTokenListenerTitle = @"Remove Last ID Token Change Listener";

/** @var kSectionTitleApp
    @brief The text for the title of the "App" section.
 */
static NSString *const kSectionTitleApp = @"APP";

/** @var kCreateUserTitle
    @brief The text of the "Create User" button.
 */
static NSString *const kCreateUserTitle = @"Create User";

/** @var kCreateUserAuthDataResultTitle
    @brief The text of the "Create User (AuthDataResult)" button.
 */
static NSString *const kCreateUserAuthDataResultTitle = @"Create User (AuthDataResult)";

/** @var kDeleteAppTitle
    @brief The text of the "Delete App" button.
 */
static NSString *const kDeleteAppTitle = @"Delete App";

/** @var kTimeAuthInitTitle
    @brief The text of the "Time Auth Initialization" button.
 */
static NSString *const kTimeAuthInitTitle = @"Time Auth Initialization";

/** @var kSectionTitleManualTests
    @brief The section title for automated manual tests.
 */
static NSString *const kSectionTitleManualTests = @"Automated (Manual) Tests";

/** @var kAutoBYOAuthTitle
    @brief The button title for automated BYOAuth operation.
 */
static NSString *const kAutoBYOAuthTitle = @"BYOAuth";

/** @var kAutoSignInGoogle
    @brief The button title for automated Google sign-in operation.
 */
static NSString *const kAutoSignInGoogle = @"Sign In With Google";

/** @var kAutoSignInFacebook
    @brief The button title for automated Facebook sign-in operation.
 */
static NSString *const kAutoSignInFacebook = @"Sign In With Facebook";

/** @var kAutoSignUpEmailPassword
    @brief The button title for automated sign-up with email/password.
 */
static NSString *const kAutoSignUpEmailPassword = @"Sign Up With Email/Password";

/** @var kAutoSignInAnonymously
    @brief The button title for automated sign-in anonymously.
 */
static NSString *const kAutoSignInAnonymously = @"Sign In Anonymously";

/** @var kAutoAccountLinking
    @brief The button title for automated account linking.
 */
static NSString *const kAutoAccountLinking = @"Link with Google";

/** @var kAutoPhoneNumberSignIn
    @brief The button title for automated Phone Number sign-in.
 */
static NSString *const kAutoPhoneNumberSignIn = @"Sign in With Phone Number";

/** @var kGitHubSignInButtonText
    @brief The button title for signing in with github.
 */
static NSString *const kGitHubSignInButtonText = @"Sign In with GitHub";

/** @var kExpiredCustomTokenUrl
    @brief The url for obtaining a valid custom token string used to test BYOAuth.
 */
static NSString *const kCustomTokenUrl = @"https://fb-sa-1211.appspot.com/token";

/** @var kCustomTokenUrl
    @brief The url for obtaining an expired custom token string used to test BYOAuth.
 */
static NSString *const kExpiredCustomTokenUrl = @"https://fb-sa-1211.appspot.com/expired_token";

/** @var kFakeDisplayPhotoUrl
    @brief The url for obtaining a display displayPhoto used for testing.
 */
static NSString *const kFakeDisplayPhotoUrl =
    @"https://www.gstatic.com/images/branding/product/1x/play_apps_48dp.png";

/** @var kFakeDisplayName
    @brief Fake display name for testing.
 */
static NSString *const kFakeDisplayName = @"John GoogleSpeed";

/** @var kFakeEmail
    @brief Fake email for testing.
 */
static NSString *const kFakeEmail =@"firemail@example.com";

/** @var kFakePassword
    @brief Fake password for testing.
 */
static NSString *const kFakePassword =@"fakePassword";

/** @var kInvalidCustomToken
    @brief The custom token string for testing BYOAuth.
 */
static NSString *const kInvalidCustomToken = @"invalid custom token.";

/** @var kSafariGoogleSignOutMessagePrompt
    @brief The message text informing user to sign-out from Google on safari before continuing.
 */
static NSString *const kSafariGoogleSignOutMessagePrompt = @"This automated test assumes that no "
    "Google account is signed in on Safari, if your are not prompted for a password, sign out on "
    "Safari and rerun the test.";

/** @var kSafariFacebookSignOutMessagePrompt
    @brief The message text informing user to sign-out from Facebook on safari before continuing.
 */
static NSString *const kSafariFacebookSignOutMessagePrompt = @"This automated test assumes that no "
    "Facebook account is signed in on Safari, if your are not prompted for a password, sign out on "
    "Safari and rerun the test.";

/** @var kUnlinkAccountMessagePrompt
    @brief The message text informing user to use an unlinked account for account linking.
 */
static NSString *const kUnlinkAccountMessagePrompt = @"Sign into gmail with an email address "
    "that has not been linked to this sample application before. Delete account if necessary.";

/** @var kPasswordResetAction
    @brief The value for password reset mode in the action code URL.
 */
static NSString *const kPasswordResetAction = @"resetPassword";

/** @var kVerifyEmailAction
    @brief The value for verify email mode in the action code URL.
 */
static NSString *const kVerifyEmailAction = @"verifyEmail";

// Declared extern in .h file.
NSString *const kCreateUserAccessibilityID = @"CreateUserAccessibilityID";

/** @var kPhoneAuthSectionTitle
    @brief The title for the phone auth section of the test app.
 */
static NSString *const kPhoneAuthSectionTitle = @"Phone Auth";

/** @var kPhoneNumberSignInTitle
    @brief The title for button to sign in with phone number.
 */
static NSString *const kPhoneNumberSignInTitle = @"Sign in With Phone Number";

/** @var kPhoneNumberSignInTitle
    @brief The title for button to sign in with phone number using reCAPTCHA.
 */
static NSString *const kPhoneNumberSignInReCaptchaTitle = @"Sign in With Phone Number (reCAPTCHA)";

/** @var kIsNewUserToggleTitle
    @brief The title for button to enable new or existing user toggle.
 */
static NSString *const kNewOrExistingUserToggleTitle = @"New or Existing User Toggle";

/** @typedef showEmailPasswordDialogCompletion
    @brief The type of block which gets called to complete the Email/Password dialog flow.
 */
typedef void (^ShowEmailPasswordDialogCompletion)(FIRAuthCredential *credential);

/** @typedef FIRTokenCallback
    @brief The type of block which gets called when a token is ready.
 */
typedef void (^FIRTokenCallback)(NSString *_Nullable token, NSError *_Nullable error);

/** @brief The request type for OOB action codes.
 */
typedef enum {
  /** No action code settings. */
  ActionCodeRequestTypeEmail,
  /** With continue URL but not handled in-app. */
  ActionCodeRequestTypeContinue,
  /** Handled in-app. */
  ActionCodeRequestTypeInApp,
} ActionCodeRequestType;

/** @category FIRAppAssociationRegistration(Deregistration)
    @brief The category for the deregistration method.
 */
@interface FIRAppAssociationRegistration (Deregistration)
/** @fn deregisteredObjectWithHost:key:
    @brief Removes the object that was registered with a particular host and key, if one exists.
    @param host The host object.
    @param key The key to specify the registered object on the host.
 */
+ (void)deregisterObjectWithHost:(id)host key:(NSString *)key;
@end

@implementation FIRAppAssociationRegistration (Deregistration)

+ (void)deregisterObjectWithHost:(id)host key:(NSString *)key {
  @synchronized(self) {
    SEL dictKey = @selector(registeredObjectWithHost:key:creationBlock:);
    NSMutableDictionary<NSString *, id> *objectsByKey = objc_getAssociatedObject(host, dictKey);
    [objectsByKey removeObjectForKey:key];
  }
}

@end

@implementation MainViewController {
  NSMutableString *_consoleString;

  /** @var _authStateDidChangeListeners
      @brief An array of handles created during calls to @c FIRAuth.addAuthStateDidChangeListener:
   */
  NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_authStateDidChangeListeners;

  /** @var _IDTokenDidChangeListeners
      @brief An array of handles created during calls to @c FIRAuth.addIDTokenDidChangeListener:
   */
  NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_IDTokenDidChangeListeners;

  /** @var _userInMemory
      @brief Acts like the "memory" function of a calculator. An operation allows sample app users
          to assign this value based on @c FIRAuth.currentUser or clear this value.
   */
  FIRUser *_userInMemory;

  /** @var _useUserInMemory
      @brief Instructs the application to use _userInMemory instead of @c FIRAuth.currentUser for
          testing operations. This allows us to test if things still work with a user who is not
          the @c FIRAuth.currentUser, and also allows us to test those things while
          @c FIRAuth.currentUser remains nil (after a sign-out) and also when @c FIRAuth.currentUser
          is non-nil (do to a subsequent sign-in.)
   */
  BOOL _useUserInMemory;

  /** @var _newUserToggle
      @brief When enabled allows login popup alert determining new or existing user.
   */
  BOOL _isNewUserToggleOn;

  /** @var _actionCodeRequestType
      @brief The type for the next action code request.
   */
  ActionCodeRequestType _actionCodeRequestType;

  /** @var _actionCodeContinueURL
      @brief The continue URL to be used in the next action code request.
   */
  NSURL *_actionCodeContinueURL;
}

/** @fn initWithNibName:bundle:
    @brief Overridden default initializer.
 */
- (id)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil {
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  if (self) {
    _actionCodeRequestType = ActionCodeRequestTypeInApp;
    _actionCodeContinueURL = [NSURL URLWithString:KCONTINUE_URL];
    _authStateDidChangeListeners = [NSMutableArray array];
    _IDTokenDidChangeListeners = [NSMutableArray array];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(authStateChangedForAuth:)
                                                 name:FIRAuthStateDidChangeNotification
                                               object:nil];
    self.useStatusBarSpinner = YES;
  }
  return self;
}

- (void)viewDidLoad {
  // Give us a circle for the image view:
  _userInfoTableViewCell.userInfoProfileURLImageView.layer.cornerRadius =
      _userInfoTableViewCell.userInfoProfileURLImageView.frame.size.width / 2.0f;
  _userInfoTableViewCell.userInfoProfileURLImageView.layer.masksToBounds = YES;
  _userInMemoryInfoTableViewCell.userInfoProfileURLImageView.layer.cornerRadius =
      _userInMemoryInfoTableViewCell.userInfoProfileURLImageView.frame.size.width / 2.0f;
  _userInMemoryInfoTableViewCell.userInfoProfileURLImageView.layer.masksToBounds = YES;
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self updateTable];
  [self updateUserInfo];
}

- (void)updateTable {
  __weak typeof(self) weakSelf = self;
  _tableViewManager.contents =
    [StaticContentTableViewContent contentWithSections:@[
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleUserDetails cells:@[
        [StaticContentTableViewCell cellWithCustomCell:_userInfoTableViewCell action:^{
          [weakSelf presentUserInfo];
        }],
        [StaticContentTableViewCell cellWithCustomCell:_userToUseCell],
        [StaticContentTableViewCell cellWithCustomCell:_userInMemoryInfoTableViewCell action:^{
          [weakSelf presentUserInMemoryInfo];
        }],
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleSettings cells:@[
        [StaticContentTableViewCell cellWithTitle:NSLocalizedString(@"SETTINGSKEY",
                                                                    kSettingsButtonTextDesription)
                                           action:^{ [weakSelf presentSettings]; }],
        [StaticContentTableViewCell cellWithTitle:kNewOrExistingUserToggleTitle
                                            value:_isNewUserToggleOn ? @"Enabled" : @"Disabled"
                                           action:^{
                                             _isNewUserToggleOn = !_isNewUserToggleOn;
                                             [self updateTable]; }],
      ]],
      [StaticContentTableViewSection sectionWithTitle:kPhoneAuthSectionTitle cells:@[
        [StaticContentTableViewCell cellWithTitle:kPhoneNumberSignInReCaptchaTitle
                                           action:^{ [weakSelf signInWithPhoneNumberWithPrompt]; }],
        [StaticContentTableViewCell cellWithTitle:kPhoneNumberSignInTitle
                                           action:^{ [weakSelf signInWithPhoneNumber]; }],
        [StaticContentTableViewCell cellWithTitle:kUpdatePhoneNumber
                                           action:^{ [weakSelf updatePhoneNumberWithPrompt]; }],
        [StaticContentTableViewCell cellWithTitle:kLinkPhoneNumber
                                           action:^{ [weakSelf linkPhoneNumberWithPrompt]; }],
        [StaticContentTableViewCell cellWithTitle:kUnlinkPhoneNumber
                                           action:^{
          [weakSelf unlinkFromProvider:FIRPhoneAuthProviderID completion:nil];
        }],
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleSignIn cells:@[
        [StaticContentTableViewCell cellWithTitle:kCreateUserTitle
                                            value:nil
                                           action:^{ [weakSelf createUser]; }
                                  accessibilityID:kCreateUserAccessibilityID],
        [StaticContentTableViewCell cellWithTitle:kCreateUserAuthDataResultTitle
                                           action:^{ [weakSelf createUserAuthDataResult]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInGoogleButtonText
                                           action:^{ [weakSelf signInGoogle]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInGoogleAndRetrieveDataButtonText
                                           action:^{ [weakSelf signInGoogleAndRetrieveData]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInFacebookButtonText
                                           action:^{ [weakSelf signInFacebook]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInFacebookAndRetrieveDataButtonText
                                           action:^{ [weakSelf signInFacebookAndRetrieveData]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInEmailPasswordButtonText
                                           action:^{ [weakSelf signInEmailPassword]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInWithCustomTokenButtonText
                                           action:^{ [weakSelf signInWithCustomToken]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInAnonymouslyButtonText
                                           action:^{ [weakSelf signInAnonymously]; }],
        [StaticContentTableViewCell cellWithTitle:kSignInAnonymouslyWithAuthResultButtonText
                                           action:^{ [weakSelf signInAnonymouslyAuthDataResult]; }],
        [StaticContentTableViewCell cellWithTitle:kGitHubSignInButtonText
                                           action:^{ [weakSelf signInWithGitHub]; }],
        [StaticContentTableViewCell cellWithTitle:kSignOutButtonText
                                           action:^{ [weakSelf signOut]; }]
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleUserActions cells:@[
        [StaticContentTableViewCell cellWithTitle:kSetDisplayNameTitle
                                           action:^{ [weakSelf setDisplayName]; }],
        [StaticContentTableViewCell cellWithTitle:kSetPhotoURLText
                                           action:^{ [weakSelf setPhotoURL]; }],
        [StaticContentTableViewCell cellWithTitle:kReloadText
                                           action:^{ [weakSelf reloadUser]; }],
        [StaticContentTableViewCell cellWithTitle:kGetProvidersForEmail
                                           action:^{ [weakSelf getProvidersForEmail]; }],
        [StaticContentTableViewCell cellWithTitle:kUpdateEmailText
                                           action:^{ [weakSelf updateEmail]; }],
        [StaticContentTableViewCell cellWithTitle:kUpdatePasswordText
                                           action:^{ [weakSelf updatePassword]; }],
        [StaticContentTableViewCell cellWithTitle:kDeleteUserText
                                           action:^{ [weakSelf deleteAccount]; }],
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleOOBActions cells:@[
        [StaticContentTableViewCell cellWithTitle:kActionCodeTypeDescription
                                            value:[self actionCodeRequestTypeString]
                                           action:^{ [weakSelf toggleActionCodeRequestType]; }],
        [StaticContentTableViewCell cellWithTitle:kContinueURLDescription
                                            value:_actionCodeContinueURL.absoluteString ?: @"(nil)"
                                           action:^{ [weakSelf changeActionCodeContinueURL]; }],
        [StaticContentTableViewCell cellWithTitle:kRequestVerifyEmail
                                           action:^{ [weakSelf requestVerifyEmail]; }],
        [StaticContentTableViewCell cellWithTitle:kRequestPasswordReset
                                           action:^{ [weakSelf requestPasswordReset]; }],
        [StaticContentTableViewCell cellWithTitle:kResetPassword
                                           action:^{ [weakSelf resetPassword]; }],
        [StaticContentTableViewCell cellWithTitle:kCheckActionCode
                                           action:^{ [weakSelf checkActionCode]; }],
        [StaticContentTableViewCell cellWithTitle:kApplyActionCode
                                           action:^{ [weakSelf applyActionCode]; }],
        [StaticContentTableViewCell cellWithTitle:kVerifyPasswordResetCode
                                           action:^{ [weakSelf verifyPasswordResetCode]; }],
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleReauthenticate cells:@[
        [StaticContentTableViewCell cellWithTitle:kReauthenticateGoogleText
                                           action:^{ [weakSelf reauthenticateGoogle]; }],
        [StaticContentTableViewCell
            cellWithTitle:kReauthenticateGoogleAndRetrieveDataText
                   action:^{ [weakSelf reauthenticateGoogleAndRetrieveData]; }],
        [StaticContentTableViewCell cellWithTitle:kReauthenticateFBText
                                           action:^{ [weakSelf reauthenticateFB]; }],
        [StaticContentTableViewCell cellWithTitle:kReauthenticateFBAndRetrieveDataText
                                           action:^{ [weakSelf reauthenticateFBAndRetrieveData]; }],
        [StaticContentTableViewCell cellWithTitle:kReauthenticateEmailText
                                           action:^{ [weakSelf reauthenticateEmailPassword]; }]
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleTokenActions cells:@[
        [StaticContentTableViewCell cellWithTitle:kTokenGetButtonText
                                           action:^{ [weakSelf getUserTokenWithForce:NO]; }],
        [StaticContentTableViewCell cellWithTitle:kTokenRefreshButtonText
                                           action:^{ [weakSelf getUserTokenWithForce:YES]; }]
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleLinkUnlinkAccounts cells:@[
        [StaticContentTableViewCell cellWithTitle:kLinkWithGoogleText
                                           action:^{ [weakSelf linkWithGoogle]; }],
        [StaticContentTableViewCell cellWithTitle:kLinkWithGoogleAndRetrieveDataText
                                           action:^{ [weakSelf linkWithGoogleAndRetrieveData]; }],
        [StaticContentTableViewCell cellWithTitle:kLinkWithFacebookText
                                           action:^{ [weakSelf linkWithFacebook]; }],
        [StaticContentTableViewCell cellWithTitle:kLinkWithFacebookAndRetrieveDataText
                                           action:^{ [weakSelf linkWithFacebookAndRetrieveData]; }],
        [StaticContentTableViewCell cellWithTitle:kLinkWithEmailPasswordText
                                           action:^{ [weakSelf linkWithEmailPassword]; }],
        [StaticContentTableViewCell cellWithTitle:kUnlinkFromGoogle
                                           action:^{
          [weakSelf unlinkFromProvider:FIRGoogleAuthProviderID completion:nil];
        }],
        [StaticContentTableViewCell cellWithTitle:kUnlinkFromFacebook
                                           action:^{
          [weakSelf unlinkFromProvider:FIRGoogleAuthProviderID completion:nil];
        }],
        [StaticContentTableViewCell cellWithTitle:kUnlinkFromEmailPassword
                                           action:^{
          [weakSelf unlinkFromProvider:FIRGoogleAuthProviderID completion:nil];
        }]
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleApp cells:@[
        [StaticContentTableViewCell cellWithTitle:kDeleteAppTitle
                                           action:^{ [weakSelf deleteApp]; }],
        [StaticContentTableViewCell cellWithTitle:kTokenGetButtonText
                                           action:^{ [weakSelf getAppTokenWithForce:NO]; }],
        [StaticContentTableViewCell cellWithTitle:kTokenRefreshButtonText
                                           action:^{ [weakSelf getAppTokenWithForce:YES]; }],
        [StaticContentTableViewCell cellWithTitle:kTimeAuthInitTitle
                                           action:^{ [weakSelf timeAuthInitialization]; }]
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleListeners cells:@[
        [StaticContentTableViewCell cellWithTitle:kAddAuthStateListenerTitle
                                           action:^{ [weakSelf addAuthStateListener]; }],
        [StaticContentTableViewCell cellWithTitle:kRemoveAuthStateListenerTitle
                                           action:^{ [weakSelf removeAuthStateListener]; }],
        [StaticContentTableViewCell cellWithTitle:kAddIDTokenListenerTitle
                                           action:^{ [weakSelf addIDTokenListener]; }],
        [StaticContentTableViewCell cellWithTitle:kRemoveIDTokenListenerTitle
                                           action:^{ [weakSelf removeIDTokenListener]; }],
      ]],
      [StaticContentTableViewSection sectionWithTitle:kSectionTitleManualTests cells:@[
        [StaticContentTableViewCell cellWithTitle:kAutoBYOAuthTitle
                                           action:^{ [weakSelf automatedBYOAuth]; }],
        [StaticContentTableViewCell cellWithTitle:kAutoSignInGoogle
                                           action:^{ [weakSelf automatedSignInGoogle]; }],
        [StaticContentTableViewCell cellWithTitle:kAutoSignInFacebook
                                           action:^{ [weakSelf automatedSignInFacebook]; }],
        [StaticContentTableViewCell cellWithTitle:kAutoSignUpEmailPassword
                                           action:^{ [weakSelf automatedEmailSignUp]; }],
        [StaticContentTableViewCell cellWithTitle:kAutoSignInAnonymously
                                           action:^{ [weakSelf automatedAnonymousSignIn]; }],
        [StaticContentTableViewCell cellWithTitle:kAutoAccountLinking
                                           action:^{ [weakSelf automatedAccountLinking]; }],
        [StaticContentTableViewCell cellWithTitle:kAutoPhoneNumberSignIn
                                           action:^{ [weakSelf automatedPhoneNumberSignIn]; }]
      ]]
    ]];
}

#pragma mark - Interface Builder Actions

- (IBAction)userToUseDidChange:(UISegmentedControl *)sender {
  _useUserInMemory = (sender.selectedSegmentIndex == 1);
}

- (IBAction)memoryPlus {
  _userInMemory = [AppManager auth].currentUser;
  [self updateUserInfo];
}

- (IBAction)memoryClear {
  _userInMemory = nil;
  [self updateUserInfo];
}

/** @fn parseURL
    @brief Parses an incoming URL into all available query items.
    @param urlString The url to be parsed.
    @return A dictionary of available query items in the target URL.
 */
static NSDictionary<NSString *, NSString *> *parseURL(NSString *urlString) {
  NSString *linkURL = [NSURLComponents componentsWithString:urlString].query;
  NSArray<NSString *> *URLComponents = [linkURL componentsSeparatedByString:@"&"];
  NSMutableDictionary<NSString *, NSString *> *queryItems =
      [[NSMutableDictionary alloc] initWithCapacity:URLComponents.count];
  for (NSString *component in URLComponents) {
    NSRange equalRange = [component rangeOfString:@"="];
    if (equalRange.location != NSNotFound) {
      NSString *queryItemKey =
          [[component substringToIndex:equalRange.location] stringByRemovingPercentEncoding];
      NSString *queryItemValue =
          [[component substringFromIndex:equalRange.location + 1] stringByRemovingPercentEncoding];
      if (queryItemKey && queryItemValue) {
        queryItems[queryItemKey] = queryItemValue;
      }
    }
  }
  return queryItems;
}

#pragma mark public methods

- (BOOL)handleIncomingLinkWithURL:(NSURL *)URL {
  // Parse the query portion of the incoming URL.
  NSDictionary<NSString *, NSString *> *queryItems =
      parseURL([NSURLComponents componentsWithString:URL.absoluteString].query);

  // Check that all necessary query items are available.
  NSString *actionCode = queryItems[@"oobCode"];
  NSString *mode = queryItems[@"mode"];
  if (!actionCode || !mode) {
    return NO;
  }
  // Handle Password Reset action.
  if ([mode isEqualToString:kPasswordResetAction]) {
    [self showTextInputPromptWithMessage:@"New Password:"
                         completionBlock:^(BOOL userPressedOK, NSString *_Nullable newPassword) {
      if (!userPressedOK || !newPassword.length) {
        [UIPasteboard generalPasteboard].string = actionCode;
        return;
      }
      [self showSpinner:^() {
        [[AppManager auth] confirmPasswordResetWithCode:actionCode
                                            newPassword:newPassword
                                             completion:^(NSError *_Nullable error) {
          [self hideSpinner:^{
            if (error) {
              [self logFailure:@"Password reset in app failed" error:error];
              [self showMessagePrompt:error.localizedDescription];
              return;
            }
            [self logSuccess:@"Password reset in app succeeded."];
            [self showMessagePrompt:@"Password reset in app succeeded."];
          }];
        }];
      }];
    }];
    return YES;
  }
  if ([mode isEqualToString:kVerifyEmailAction]) {
    [self showMessagePromptWithTitle:@"Tap OK to verify email"
                             message:actionCode
                    showCancelButton:YES
                          completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
      if (!userPressedOK) {
        return;
      }
      [self showSpinner:^() {
        [[AppManager auth] applyActionCode:actionCode completion:^(NSError *_Nullable error) {
          [self hideSpinner:^{
            if (error) {
              [self logFailure:@"Verify email in app failed" error:error];
              [self showMessagePrompt:error.localizedDescription];
              return;
            }
            [self logSuccess:@"Verify email in app succeeded."];
            [self showMessagePrompt:@"Verify email in app succeeded."];
          }];
        }];
      }];
    }];
    return YES;
  }
  return NO;
}

#pragma mark - Actions

/** @fn signInWithProvider:provider:
    @brief Perform sign in with credential operataion, for given auth provider.
    @param provider The auth provider.
    @param callback The callback to continue the flow which executed this sign-in.
 */
- (void)signInWithProvider:(nonnull id<AuthProvider>)provider callback:(void(^)(void))callback {
  if (!provider) {
    [self logFailedTest:@"A valid auth provider was not provided to the signInWithProvider."];
    return;
  }
  [provider getAuthCredentialWithPresentingViewController:self
                                                 callback:^(FIRAuthCredential *credential,
                                                            NSError *error) {
    if (!credential) {
      [self logFailedTest:@"The test needs a valid credential to continue."];
      return;
    }
    [[AppManager auth] signInWithCredential:credential completion:^(FIRUser *_Nullable user,
                                                                    NSError *_Nullable error) {
      if (error) {
        [self logFailure:@"sign-in with provider failed" error:error];
        [self logFailedTest:@"Sign-in should succeed"];
        return;
      } else {
        [self logSuccess:@"sign-in with provider succeeded."];
        callback();
      }
    }];
  }];
}

/** @fn automatedSignInGoogle
    @brief Automatically executes the manual test for sign-in with Google.
 */
- (void)automatedSignInGoogle {
  [self showMessagePromptWithTitle:kAutoSignInGoogle
                           message:kSafariGoogleSignOutMessagePrompt
                  showCancelButton:NO
                        completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    FIRAuth *auth = [AppManager auth];
    if (!auth) {
      [self logFailedTest:@"Could not obtain auth object."];
      return;
    }
    [auth signOut:NULL];
    [self log:@"INITIATING AUTOMATED MANUAL TEST FOR GOOGLE SIGN IN:"];
    [self signInWithProvider:[AuthProviders google] callback:^{
      [self logSuccess:@"sign-in with Google provider succeeded."];
      [auth signOut:NULL];
      [self signInWithProvider:[AuthProviders google] callback:^{
        [self logSuccess:@"sign-in with Google provider succeeded."];
        [self updateEmailPasswordWithCompletion:^{
          [self automatedSignInGoogleDisplayNamePhotoURL];
        }];
      }];
    }];
  }];
}

/** @fn automatedSignInGoogleDisplayNamePhotoURL
    @brief Automatically executes the manual test for setting email and password for sign in with
        Google.
 */
- (void)automatedSignInGoogleDisplayNamePhotoURL {
  [self signInWithProvider:[AuthProviders google] callback:^{
    [self updateDisplayNameAndPhotoURlWithCompletion:^{
      [self log:@"FINISHED AUTOMATED MANUAL TEST FOR SIGN-IN WITH GOOGlE."];
      [self reloadUser];
    }];
  }];
}

/** @fn automatedSignInFacebook
    @brief Automatically executes the manual test for sign-in with Facebook.
 */
- (void)automatedSignInFacebook {
  [self showMessagePromptWithTitle:kAutoSignInFacebook
                           message:kSafariFacebookSignOutMessagePrompt
                  showCancelButton:NO
                        completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    FIRAuth *auth = [AppManager auth];
    if (!auth) {
      [self logFailedTest:@"Could not obtain auth object."];
      return;
    }
    [auth signOut:NULL];
    [self log:@"INITIATING AUTOMATED MANUAL TEST FOR FACEBOOK SIGN IN:"];
    [self signInWithProvider:[AuthProviders facebook] callback:^{
      [self logSuccess:@"sign-in with Facebook provider succeeded."];
      [auth signOut:NULL];
      [self signInWithProvider:[AuthProviders facebook] callback:^{
        [self logSuccess:@"sign-in with Facebook provider succeeded."];
        [self updateEmailPasswordWithCompletion:^{
          [self automatedSignInFacebookDisplayNamePhotoURL];
        }];
      }];
    }];
  }];
}

/** @fn automatedPhoneNumberSignIn
    @brief Automatically executes the manual test for sign-in with phone number.
 */
- (void)automatedPhoneNumberSignIn {
  [self log:@"Automated phone number sign in"];
  FIRAuth *auth = [AppManager auth];
  if (!auth) {
    [self logFailedTest:@"Could not obtain auth object."];
    return;
  }
  [auth signOut:NULL];
  [self log:@"INITIATING AUTOMATED MANUAL TEST FOR PHONE NUMBER SIGN IN:"];
  [self commonPhoneNumberInputWithTitle:@"Phone for automation"
                             Completion:^(NSString *_Nullable phone) {
   [self signInWithPhoneNumber:phone completion:^(NSError *error) {
     if (error) {
       [self logFailedTest:@"Could not sign in with phone number reCAPTCHA."];
     }
     [self logSuccess:@"sign-in with phone number reCAPTCHA test succeeded."];
     [auth signOut:NULL];
     [self signInWithPhoneNumber:phone completion:^(NSError *error) {
       if (error) {
         [self logFailedTest:@"Could not sign in with phone number reCAPTCHA."];
       }
       [self logSuccess:@"second sign-in with phone number reCAPTCHA test succeeded."];
       [self updatePhoneNumber:phone completion:^(NSError *error) {
         if (error) {
           [self logFailedTest:@"Could not update phone number."];
         }
         [self logSuccess:@"update phone number test succeeded."];
         [self unlinkFromProvider:FIRPhoneAuthProviderID completion:^(NSError *error) {
           if (error) {
             [self logFailedTest:@"Could not unlink phone number."];
           }
           [self logSuccess:@"unlink phone number test succeeded."];
           [self linkPhoneNumber:phone completion:^(NSError *error) {
             if (error) {
               [self logFailedTest:@"Could not link phone number."];
             }
             [self logSuccess:@"link phone number test succeeded."];
             [self log:@"FINISHED AUTOMATED MANUAL TEST FOR PHONE NUMBER SIGN IN."];
           }];
         }];
       }];
     }];
   }];
 }];
}


/** @fn automatedEmailSignUp
    @brief Automatically executes the manual test for sign-up with email/password.
 */
- (void)automatedEmailSignUp {
  [self log:@"INITIATING AUTOMATED MANUAL TEST FOR FACEBOOK SIGN IN:"];
  FIRAuth *auth = [AppManager auth];
  if (!auth) {
    [self logFailedTest:@"Could not obtain auth object."];
    return;
  }
  [self signUpNewEmail:kFakeEmail password:kFakePassword callback:^(FIRUser *_Nullable user,
                                                                    NSError *_Nullable error) {
    if (error) {
      [self logFailedTest: @" Email/Password Account account creation failed"];
      return;
    }
    [auth signOut:NULL];
    FIRAuthCredential *credential = [FIREmailAuthProvider credentialWithEmail:kFakeEmail
                                                                     password:kFakePassword];
    [auth signInWithCredential:credential
                     completion:^(FIRUser *_Nullable user,
                                  NSError *_Nullable error) {
      if (error) {
        [self logFailure:@"sign-in with Email/Password failed" error:error];
        [self logFailedTest:@"sign-in with Email/Password should succeed."];
        return;
      }
      [self logSuccess:@"sign-in with Email/Password succeeded."];
      [self log:@"FINISHED AUTOMATED MANUAL TEST FOR SIGN-IN WITH EMAIL/PASSWORD."];
      // Delete the user so that we can reuse the fake email address for subsequent tests.
      [auth.currentUser deleteWithCompletion:^(NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"Failed to delete user" error:error];
          [self logFailedTest:@"Deleting a user that was recently signed-in should succeed."];
          return;
        }
        [self logSuccess:@"User deleted."];
      }];
    }];
  }];
}

/** @fn automatedAnonymousSignIn
    @brief Automatically executes the manual test for sign-in anonymously.
 */
- (void)automatedAnonymousSignIn {
  [self log:@"INITIATING AUTOMATED MANUAL TEST FOR ANONYMOUS SIGN IN:"];
  FIRAuth *auth = [AppManager auth];
  if (!auth) {
    [self logFailedTest:@"Could not obtain auth object."];
    return;
  }
  [auth signOut:NULL];
  [self signInAnonymouslyWithCallback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
    if (user) {
      NSString *anonymousUID = user.uid;
      [self signInAnonymouslyWithCallback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
        if (![user.uid isEqual:anonymousUID]) {
          [self logFailedTest:@"Consecutive anonymous sign-ins should yeild the same User ID"];
          return;
        }
        [self log:@"FINISHED AUTOMATED MANUAL TEST FOR ANONYMOUS SIGN IN."];
      }];
    }
  }];
}

/** @fn signInAnonymouslyWithCallback:
    @brief Performs anonymous sign in and then executes callback.
    @param callback The callback to be executed.
 */
- (void)signInAnonymouslyWithCallback:(nullable FIRAuthResultCallback)callback {
  FIRAuth *auth = [AppManager auth];
  if (!auth) {
    [self logFailedTest:@"Could not obtain auth object."];
    return;
  }
  [auth signInAnonymouslyWithCompletion:^(FIRUser *_Nullable user,
                                          NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"sign-in anonymously failed" error:error];
      [self logFailedTest:@"Recently signed out user should be able to sign in anonymously."];
      return;
    }
    [self logSuccess:@"sign-in anonymously succeeded."];
    if (callback) {
      callback(user, nil);
    }
  }];
}

/** @fn automatedAccountLinking
    @brief Automatically executes the manual test for account linking.
 */
- (void)automatedAccountLinking {
  [self log:@"INITIATING AUTOMATED MANUAL TEST FOR ACCOUNT LINKING:"];
  FIRAuth *auth = [AppManager auth];
  if (!auth) {
    [self logFailedTest:@"Could not obtain auth object."];
    return;
  }
  [auth signOut:NULL];
  [self signInAnonymouslyWithCallback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
    if (user) {
      NSString *anonymousUID = user.uid;
      [self showMessagePromptWithTitle:@"Sign In Instructions"
                               message:kUnlinkAccountMessagePrompt
                      showCancelButton:NO
                            completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
        [[AuthProviders google]
            getAuthCredentialWithPresentingViewController:self
                                                 callback:^(FIRAuthCredential *credential,
                                                            NSError *error) {
          if (credential) {
            [user linkWithCredential:credential completion:^(FIRUser *user, NSError *error) {
              if (error) {
                [self logFailure:@"link auth provider failed" error:error];
                [self logFailedTest:@"Account needs to be linked to complete the test."];
                return;
              }
              [self logSuccess:@"link auth provider succeeded."];
              if (user.isAnonymous) {
                [self logFailure:@"link auth provider failed, user still anonymous" error:error];
                [self logFailedTest:@"Account needs to be linked to complete the test."];
              }
              if (![user.uid isEqual:anonymousUID]){
                [self logFailedTest:@"link auth provider failed, UID's are different. Make sure "
                    "you link an account that has NOT been Linked nor Signed-In before."];
                return;
              }
              [self log:@"FINISHED AUTOMATED MANUAL TEST FOR ACCOUNT LINKING."];
            }];
          }
       }];
     }];
    }
  }];
}

/** @fn automatedSignInFacebookDisplayNamePhotoURL
    @brief Automatically executes the manual test for setting email and password for sign-in with
        Facebook.
 */
- (void)automatedSignInFacebookDisplayNamePhotoURL {
  [self signInWithProvider:[AuthProviders facebook] callback:^{
    [self updateDisplayNameAndPhotoURlWithCompletion:^{
      [self log:@"FINISHED AUTOMATED MANUAL TEST FOR SIGN-IN WITH FACEBOOK."];
      [self reloadUser];
    }];
  }];
}

/** @fn automatedBYOauth
    @brief Automatically executes the manual test for BYOAuth.
 */
- (void)automatedBYOAuth {
  [self log:@"INITIATING AUTOMATED MANUAL TEST FOR BYOAUTH:"];
  [self showSpinner:^{
    NSError *error;
    NSString *customToken = [NSString stringWithContentsOfURL:[NSURL URLWithString:kCustomTokenUrl]
                                                     encoding:NSUTF8StringEncoding
                                                        error:&error];
    NSString *expiredCustomToken =
      [NSString stringWithContentsOfURL:[NSURL URLWithString:kExpiredCustomTokenUrl]
                               encoding:NSUTF8StringEncoding
                                  error:&error];
    [self hideSpinner:^{
      if (error) {
        [self log:@"There was an error retrieving the custom token."];
        return;
      }
      FIRAuth *auth = [AppManager auth];
      [auth signInWithCustomToken:customToken
                       completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"sign-in with custom token failed" error:error];
          [self logFailedTest:@"A fresh custom token should succeed in signing-in."];
          return;
        }
        [self logSuccess:@"sign-in with custom token succeeded."];
        [auth.currentUser getIDTokenForcingRefresh:NO
                                        completion:^(NSString *_Nullable token,
                                                     NSError *_Nullable error) {
          if (error) {
            [self logFailure:@"refresh token failed" error:error];
            [self logFailedTest:@"Refresh token should be available."];
            return;
          }
          [self logSuccess:@"refresh token succeeded."];
          [auth signOut:NULL];
          [auth signInWithCustomToken:expiredCustomToken
                           completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
            if (!error) {
              [self logSuccess:@"sign-in with custom token succeeded."];
              [self logFailedTest:@"sign-in with an expired custom token should NOT succeed."];
              return;
            }
            [self logFailure:@"sign-in with custom token failed" error:error];
            [auth signInWithCustomToken:kInvalidCustomToken
                             completion:^(FIRUser *_Nullable user,
                                          NSError *_Nullable error) {
              if (!error) {
                [self logSuccess:@"sign-in with custom token succeeded."];
                [self logFailedTest:@"sign-in with an invalid custom token should NOT succeed."];
                return;
              }
              [self logFailure:@"sign-in with custom token failed" error:error];
              //next step of automated test.
              [self automatedBYOAuthEmailPassword];
            }];
          }];
        }];
      }];
    }];
  }];
}

/** @fn automatedBYOAuthEmailPassword
    @brief Automatically executes the manual test for setting email and password in BYOAuth.
 */
- (void)automatedBYOAuthEmailPassword {
  [self showSpinner:^{
    NSError *error;
    NSString *customToken = [NSString stringWithContentsOfURL:[NSURL URLWithString:kCustomTokenUrl]
                                                     encoding:NSUTF8StringEncoding
                                                        error:&error];
    [self hideSpinner:^{
      if (error) {
        [self log:@"There was an error retrieving the custom token."];
        return;
      }
      [[AppManager auth] signInWithCustomToken:customToken
                                    completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"sign-in with custom token failed" error:error];
          [self logFailedTest:@"A fresh custom token should succeed in signing-in."];
          return;
        }
        [self logSuccess:@"sign-in with custom token succeeded."];
        [self updateEmailPasswordWithCompletion:^{
          [self automatedBYOAuthDisplayNameAndPhotoURl];
        }];
      }];
    }];
  }];
}

/** @fn automatedBYOAuthDisplayNameAndPhotoURl
    @brief Automatically executes the manual test for setting display name and photo url in BYOAuth.
 */
- (void)automatedBYOAuthDisplayNameAndPhotoURl {
  [self showSpinner:^{
    NSError *error;
    NSString *customToken = [NSString stringWithContentsOfURL:[NSURL URLWithString:kCustomTokenUrl]
                                                     encoding:NSUTF8StringEncoding
                                                        error:&error];
    [self hideSpinner:^{
      if (error) {
        [self log:@"There was an error retrieving the custom token."];
        return;
      }
      [[AppManager auth] signInWithCustomToken:customToken
                                    completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"sign-in with custom token failed" error:error];
          [self logFailedTest:@"A fresh custom token should succeed in signing-in."];
          return;
        }
        [self logSuccess:@"sign-in with custom token succeeded."];
        [self updateDisplayNameAndPhotoURlWithCompletion:^{
          [self log:@"FINISHED AUTOMATED MANUAL TEST FOR BYOAUTH."];
          [self reloadUser];
        }];
      }];
    }];
  }];
}

/** @fn updateEmailPasswordWithCompletion:
    @brief Updates email and password for automatic manual tests, and signs user in with new email
        and password.
    @param completion The completion block to continue the automatic test flow.
 */
- (void)updateEmailPasswordWithCompletion:(void(^)(void))completion {
  FIRAuth *auth = [AppManager auth];
  [auth.currentUser updateEmail:kFakeEmail completion:^(NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"update email failed" error:error];
      [self logFailedTest:@"Update email should succeed when properly signed-in."];
      return;
    }
    [self logSuccess:@"update email succeeded."];
    [auth.currentUser updatePassword:kFakePassword completion:^(NSError *_Nullable error) {
      if (error) {
        [self logFailure:@"update password failed" error:error];
        [self logFailedTest:@"Update password should succeed when properly signed-in."];
        return;
      }
      [self logSuccess:@"update password succeeded."];
      [auth signOut:NULL];
      FIRAuthCredential *credential =
        [FIREmailAuthProvider credentialWithEmail:kFakeEmail password:kFakePassword];
      [auth signInWithCredential:credential
                       completion:^(FIRUser *_Nullable user,
                                    NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"sign-in with Email/Password failed" error:error];
          [self logFailedTest:@"sign-in with Email/Password should succeed."];
          return;
        }
        [self logSuccess:@"sign-in with Email/Password succeeded."];
        // Delete the user so that we can reuse the fake email address for subsequent tests.
        [auth.currentUser deleteWithCompletion:^(NSError *_Nullable error) {
          if (error) {
            [self logFailure:@"Failed to delete user." error:error];
            [self logFailedTest:@"Deleting a user that was recently signed-in should succeed"];
            return;
          }
        [self logSuccess:@"User deleted."];
        completion();
        }];
      }];
    }];
  }];
}

/** @fn updateDisplayNameAndPhotoURlWithCompletion:
    @brief Automatically executes the manual test for setting displayName and photoUrl.
    @param completion The completion block to continue the automatic test flow.
 */
- (void)updateDisplayNameAndPhotoURlWithCompletion:(void(^)(void))completion {
  FIRAuth *auth = [AppManager auth];
  FIRUserProfileChangeRequest *changeRequest = [auth.currentUser profileChangeRequest];
  changeRequest.photoURL = [NSURL URLWithString:kFakeDisplayPhotoUrl];
  [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"set photo URL failed" error:error];
      [self logFailedTest:@"Change photo Url should succeed when signed-in."];
      return;
    }
    [self logSuccess:@"set PhotoURL succeeded."];
    FIRUserProfileChangeRequest *changeRequest = [auth.currentUser profileChangeRequest];
    changeRequest.displayName = kFakeDisplayName;
    [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
      if (error) {
        [self logFailure:@"set display name failed" error:error];
        [self logFailedTest:@"Change display name should succeed when signed-in."];
        return;
      }
      [self logSuccess:@"set display name succeeded."];
      completion();
    }];
  }];
}

/** @fn addAuthStateListener
    @brief Adds an auth state did change listener (block).
 */
- (void)addAuthStateListener {
  __weak typeof(self) weakSelf = self;
  NSUInteger index = _authStateDidChangeListeners.count;
  [self log:[NSString stringWithFormat:@"Auth State Did Change Listener #%lu was added.",
                                       (unsigned long)index]];
  FIRAuthStateDidChangeListenerHandle handle =
      [[AppManager auth] addAuthStateDidChangeListener:^(FIRAuth *_Nonnull auth,
                                                         FIRUser *_Nullable user) {
        [weakSelf log:[NSString stringWithFormat:
            @"Auth State Did Change Listener #%lu was invoked on user '%@'.",
            (unsigned long)index, user.uid]];
      }];
  [_authStateDidChangeListeners addObject:handle];
}

/** @fn removeAuthStateListener
    @brief Removes an auth state did change listener (block).
 */
- (void)removeAuthStateListener {
  if (!_authStateDidChangeListeners.count) {
    [self log:@"No remaining Auth State Did Change Listeners."];
    return;
  }
  NSUInteger index = _authStateDidChangeListeners.count - 1;
  FIRAuthStateDidChangeListenerHandle handle = _authStateDidChangeListeners.lastObject;
  [[AppManager auth] removeAuthStateDidChangeListener:handle];
  [_authStateDidChangeListeners removeObject:handle];
  NSString *logString =
      [NSString stringWithFormat:@"Auth State Did Change Listener #%lu was removed.",
                                 (unsigned long)index];
  [self log:logString];
}

/** @fn addIDTokenListener
    @brief Adds an ID token did change listener (block).
 */
- (void)addIDTokenListener {
  __weak typeof(self) weakSelf = self;
  NSUInteger index = _IDTokenDidChangeListeners.count;
  [self log:[NSString stringWithFormat:@"ID Token Did Change Listener #%lu was added.",
                                       (unsigned long)index]];
  FIRIDTokenDidChangeListenerHandle handle =
      [[AppManager auth] addIDTokenDidChangeListener:^(FIRAuth *_Nonnull auth,
                                                       FIRUser *_Nullable user) {
        [weakSelf log:[NSString stringWithFormat:
            @"ID Token Did Change Listener #%lu was invoked on user '%@'.",
            (unsigned long)index, user.uid]];
      }];
  [_IDTokenDidChangeListeners addObject:handle];
}

/** @fn removeIDTokenListener
    @brief Removes an ID token did change listener (block).
 */
- (void)removeIDTokenListener {
  if (!_IDTokenDidChangeListeners.count) {
    [self log:@"No remaining ID Token Did Change Listeners."];
    return;
  }
  NSUInteger index = _IDTokenDidChangeListeners.count - 1;
  FIRIDTokenDidChangeListenerHandle handle = _IDTokenDidChangeListeners.lastObject;
  [[AppManager auth] removeIDTokenDidChangeListener:handle];
  [_IDTokenDidChangeListeners removeObject:handle];
  NSString *logString =
      [NSString stringWithFormat:@"ID Token Did Change Listener #%lu was removed.",
                                 (unsigned long)index];
  [self log:logString];
}

/** @fn log:
    @brief Prints a log message to the sample app console.
    @param string The string to add to the console.
 */
- (void)log:(NSString *)string {
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
  NSString *date = [dateFormatter stringFromDate:[NSDate date]];
  if (!_consoleString) {
    _consoleString = [NSMutableString string];
  }
  [_consoleString appendString:[NSString stringWithFormat:@"%@  %@\n", date, string]];
  _consoleTextView.text = _consoleString;

  CGRect targetRect = CGRectMake(0, _consoleTextView.contentSize.height - 1, 1, 1);
  [_consoleTextView scrollRectToVisible:targetRect animated:YES];
}

/** @fn logSuccess:
    @brief Wraps a string into a succeful log message format.
    @param string Part of the log message.
    @remarks The @string parameter should be a string ending with a period, as it is the end of the
        log message.
 */
- (void)logSuccess:(NSString *)string {
  [self log:[NSString stringWithFormat:@"SUCCESS: %@", string]];
}

/** @fn logFailure:
    @brief Wraps a string into a failed log message format.
    @param string Part of the message to wrap.
    @remarks The @string parameter should be a string that NEVER ends with a period, as it is
        guaranteed not to be the last part fo the log message.
 */
- (void)logFailure:(NSString *)string error:(NSError *) error {
  NSString *message =
      [NSString stringWithFormat:@"FAILURE: %@  Error Description: %@.", string, error.description];
  [self log:message];
}

/** @fn logTestFailed
    @brief Logs test failure to the console.
    @param reason The reason why the test is considered a failure.
    @remarks The calling method should immediately terminate after invoking this method i.e by
        return statement or end of fucntions. The @reason parameter should be a string ending with a
        period, as it is the end of the log message.
 */
- (void)logFailedTest:( NSString *_Nonnull )reason {
  [self log:[NSString stringWithFormat:@"FAILIURE: TEST FAILED - %@", reason]];
}

/** @fn presentSettings
    @brief Invoked when the settings row is pressed.
 */
- (void)presentSettings {
  SettingsViewController *settingsViewController = [[SettingsViewController alloc]
      initWithNibName:NSStringFromClass([SettingsViewController class])
               bundle:nil];
  [self presentViewController:settingsViewController animated:YES completion:nil];
}

/** @fn presentUserInfo
    @brief Invoked when the user info row is pressed.
 */
- (void)presentUserInfo {
  UserInfoViewController *userInfoViewController =
      [[UserInfoViewController alloc] initWithUser:[AppManager auth].currentUser];
  [self presentViewController:userInfoViewController animated:YES completion:nil];
}

/** @fn presentUserInMemoryInfo
    @brief Invoked when the user in memory info row is pressed.
 */
- (void)presentUserInMemoryInfo {
  UserInfoViewController *userInfoViewController =
      [[UserInfoViewController alloc] initWithUser:_userInMemory];
  [self presentViewController:userInfoViewController animated:YES completion:nil];
}

/** @fn signInGoogle
    @brief Invoked when "Sign in with Google" row is pressed.
 */
- (void)signInGoogle {
  [self signinWithProvider:[AuthProviders google] retrieveData:NO];
}

/** @fn signInGoogleAndRetrieveData
    @brief Invoked when "Sign in with Google and retrieve data" row is pressed.
 */
- (void)signInGoogleAndRetrieveData {
  [self signinWithProvider:[AuthProviders google] retrieveData:YES];
}

/** @fn signInFacebook
    @brief Invoked when "Sign in with Facebook" row is pressed.
 */
- (void)signInFacebook {
  [self signinWithProvider:[AuthProviders facebook] retrieveData:NO];
}

/** @fn signInFacebookAndRetrieveData
    @brief Invoked when "Sign in with Facebook and retrieve data" row is pressed.
 */
- (void)signInFacebookAndRetrieveData {
  [self signinWithProvider:[AuthProviders facebook] retrieveData:YES];
}

/** @fn signInEmailPassword
    @brief Invoked when "sign in with Email/Password" row is pressed.
 */
- (void)signInEmailPassword {
  [self showTextInputPromptWithMessage:@"Email Address:"
                          keyboardType:UIKeyboardTypeEmailAddress
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
    if (!userPressedOK || !email.length) {
      return;
    }
    [self showTextInputPromptWithMessage:@"Password:"
                         completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
      if (!userPressedOK) {
        return;
      }
      FIRAuthCredential *credential =
          [FIREmailAuthProvider credentialWithEmail:email
                                                   password:password];
      [self showSpinner:^{
        [[AppManager auth] signInWithCredential:credential
                                     completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
          [self hideSpinner:^{
            if (error) {
              [self logFailure:@"sign-in with Email/Password failed" error:error];
            } else {
              [self logSuccess:@"sign-in with Email/Password succeeded."];
            }
            [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In Error" error:error];
          }];
        }];
      }];
    }];
  }];
}

/** @fn signUpNewEmail
    @brief Invoked if sign-in is attempted with new email/password.
    @remarks Should only be called if @c FIRAuthErrorCodeInvalidEmail is encountered on attepmt to
        sign in with email/password.
 */
- (void)signUpNewEmail:(NSString *)email
              password:(NSString *)password
              callback:(nullable FIRAuthResultCallback)callback {
  [[AppManager auth] createUserWithEmail:email
                                password:password
                              completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"sign-up with Email/Password failed" error:error];
      if (callback) {
        callback(nil, error);
      }
    } else {
      [self logSuccess:@"sign-up with Email/Password succeeded."];
      if (callback) {
        callback(user, nil);
      }
    }
    [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In" error:error];
  }];
}

/** @fn signInWithCustomToken
    @brief Signs the user in using a manually-entered custom token.
 */
- (void)signInWithCustomToken {
  CustomTokenDataEntryViewControllerCompletion action =
      ^(BOOL cancelled, NSString *_Nullable userEnteredTokenText) {
        if (cancelled) {
          [self log:@"CANCELLED:sign-in with custom token cancelled."];
          return;
        }

        [self doSignInWithCustomToken:userEnteredTokenText];
      };
  CustomTokenDataEntryViewController *dataEntryViewController =
      [[CustomTokenDataEntryViewController alloc] initWithCompletion:action];
  [self presentViewController:dataEntryViewController animated:YES completion:nil];
}

/** @fn signOut
    @brief Signs the user out.
 */
- (void)signOut {
  [[AuthProviders google] signOut];
  [[AuthProviders facebook] signOut];
  [[AppManager auth] signOut:NULL];
}

/** @fn deleteAccount
    @brief Deletes the current user account and signs the user out.
 */
- (void)deleteAccount {
  FIRUser *user = [self user];
  [user deleteWithCompletion:^(NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"delete account failed" error:error];
    }
    [self showTypicalUIForUserUpdateResultsWithTitle:kDeleteUserText error:error];
  }];
}

/** @fn reauthenticateGoogle
    @brief Asks the user to reauthenticate with Google.
 */
- (void)reauthenticateGoogle {
  [self reauthenticate:[AuthProviders google] retrieveData:NO];
}

/** @fn reauthenticateGoogleAndRetrieveData
    @brief Asks the user to reauthenticate with Google and retrieve additional data.
 */
- (void)reauthenticateGoogleAndRetrieveData {
  [self reauthenticate:[AuthProviders google] retrieveData:YES];
}

/** @fn reauthenticateFB
    @brief Asks the user to reauthenticate with Facebook.
 */
- (void)reauthenticateFB {
  [self reauthenticate:[AuthProviders facebook] retrieveData:NO];
}

/** @fn reauthenticateFBAndRetrieveData
    @brief Asks the user to reauthenticate with Facebook and retrieve additional data.
 */
- (void)reauthenticateFBAndRetrieveData {
  [self reauthenticate:[AuthProviders facebook] retrieveData:YES];
}

/** @fn reauthenticateEmailPassword
    @brief Asks the user to reauthenticate with email/password.
 */
- (void)reauthenticateEmailPassword {
  FIRUser *user = [self user];
  if (!user) {
    NSString *title = @"Missing User";
    NSString *message = @"There is no signed-in email/password user.";
    [self showMessagePromptWithTitle:title message:message showCancelButton:NO completion:nil];
    return;
  }
  [self showEmailPasswordDialogWithCompletion:^(FIRAuthCredential *credential) {
    [self showSpinner:^{
      [[self user] reauthenticateWithCredential:credential
                                     completion:^(NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"reauthicate with email/password failed" error:error];
        } else {
          [self logSuccess:@"reauthicate with email/password succeeded."];
        }
        [self hideSpinner:^{
          [self showTypicalUIForUserUpdateResultsWithTitle:kReauthenticateEmailText error:error];
        }];
      }];
    }];
  }];
}

/** @fn reauthenticate:
    @brief Reauthenticates user.
    @param authProvider The auth provider to use for reauthentication.
    @param retrieveData Defines if additional provider data should be read.
 */
- (void)reauthenticate:(id<AuthProvider>)authProvider retrieveData:(BOOL)retrieveData {
  FIRUser *user = [self user];
  if (!user) {
    NSString *provider = @"Firebase";
    if ([authProvider isKindOfClass:[GoogleAuthProvider class]]) {
      provider = @"Google";
    } else if ([authProvider isKindOfClass:[FacebookAuthProvider class]]) {
      provider = @"Facebook";
    }
    NSString *title = @"Missing User";
    NSString *message =
        [NSString stringWithFormat:@"There is no signed-in %@ user.", provider];
    [self showMessagePromptWithTitle:title message:message showCancelButton:NO completion:nil];
    return;
  }
  [authProvider getAuthCredentialWithPresentingViewController:self
                                                     callback:^(FIRAuthCredential *credential,
                                                                NSError *error) {
    if (credential) {
      FIRAuthDataResultCallback completion = ^(FIRAuthDataResult *_Nullable authResult,
                                               NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"reauthenticate operation failed" error:error];
        } else {
          [self logSuccess:@"reauthenticate operation succeeded."];
        }
        if (authResult.additionalUserInfo) {
          [self logSuccess:[self stringWithAdditionalUserInfo:authResult.additionalUserInfo]];
        }
        [self showTypicalUIForUserUpdateResultsWithTitle:@"Reauthenticate" error:error];
      };
      FIRUserProfileChangeCallback callback = ^(NSError *_Nullable error) {
        completion(nil, error);
      };
      if (retrieveData) {
        [user reauthenticateAndRetrieveDataWithCredential:credential completion:completion];
      } else {
        [user reauthenticateWithCredential:credential completion:callback];
      }
    }
  }];
}

/** @fn signinWithProvider:
    @brief Signs in the user with provided auth provider.
    @param authProvider The auth provider to use for sign-in.
    @param retrieveData Defines if additional provider data should be read.
 */
- (void)signinWithProvider:(id<AuthProvider>)authProvider retrieveData:(BOOL)retrieveData {
  FIRAuth *auth = [AppManager auth];
  if (!auth) {
    return;
  }
  [authProvider getAuthCredentialWithPresentingViewController:self
                                                     callback:^(FIRAuthCredential *credential,
                                                                NSError *error) {
    if (credential) {
      FIRAuthDataResultCallback completion = ^(FIRAuthDataResult *_Nullable authResult,
                                               NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"sign-in with provider failed" error:error];
        } else {
          [self logSuccess:@"sign-in with provider succeeded."];
        }
        if (authResult.additionalUserInfo) {
          [self logSuccess:[self stringWithAdditionalUserInfo:authResult.additionalUserInfo]];
          if (_isNewUserToggleOn) {
            NSString *newUserString = authResult.additionalUserInfo.isNewUser ?
                @"New user" : @"Existing user";
            [self showMessagePromptWithTitle:@"New or Existing"
                                     message:newUserString
                            showCancelButton:NO
                                  completion:nil];
          }
        }
        [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In" error:error];
      };
      FIRAuthResultCallback callback = ^(FIRUser *_Nullable user,
                                         NSError *_Nullable error) {
        completion(nil, error);
      };
      if (retrieveData) {
        [auth signInAndRetrieveDataWithCredential:credential completion:completion];
      } else {
        [auth signInWithCredential:credential completion:callback];
      }
    }
  }];
}

/** @fn tokenCallback
    @return A callback block to show the token.
 */
- (FIRAuthTokenCallback)tokenCallback {
  return ^(NSString *_Nullable token, NSError *_Nullable error) {
    if (error) {
      [self showMessagePromptWithTitle:kTokenRefreshErrorAlertTitle
                               message:error.localizedDescription
                      showCancelButton:NO
                            completion:nil];
      [self logFailure:@"refresh token failed" error:error];
      return;
    }
    [self logSuccess:@"refresh token succeeded."];
    [self showMessagePromptWithTitle:kTokenRefreshedAlertTitle
                             message:token
                    showCancelButton:NO
                          completion:nil];
  };
}

/** @fn getUserTokenWithForce:
    @brief Gets the token from @c FIRUser , optionally a refreshed one.
    @param force Whether the refresh is forced or not.
 */
- (void)getUserTokenWithForce:(BOOL)force {
  [[self user] getIDTokenForcingRefresh:force completion:[self tokenCallback]];
}

/** @fn getAppTokenWithForce:
    @brief Gets the token from @c FIRApp , optionally a refreshed one.
    @param force Whether the refresh is forced or not.
 */
- (void)getAppTokenWithForce:(BOOL)force {
  [[FIRApp defaultApp] getTokenForcingRefresh:force withCallback:[self tokenCallback]];
}

/** @fn setDisplayName
    @brief Changes the display name of the current user.
 */
- (void)setDisplayName {
  [self showTextInputPromptWithMessage:@"Display Name:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }
    [self showSpinner:^{
      FIRUserProfileChangeRequest *changeRequest = [[self user] profileChangeRequest];
      changeRequest.displayName = userInput;
      [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
        [self hideSpinner:^{
          if (error) {
            [self logFailure:@"set display name failed" error:error];
          } else {
            [self logSuccess:@"set display name succeeded."];
          }
          [self showTypicalUIForUserUpdateResultsWithTitle:kSetDisplayNameTitle error:error];
        }];
      }];
    }];
  }];
}

/** @fn setPhotoURL
    @brief Changes the photo url of the current user.
 */
- (void)setPhotoURL {
  [self showTextInputPromptWithMessage:@"Photo URL:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }

    [self showSpinner:^{
      FIRUserProfileChangeRequest *changeRequest = [[self user] profileChangeRequest];
      changeRequest.photoURL = [NSURL URLWithString:userInput];
      [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"set photo URL failed" error:error];
        } else {
          [self logSuccess:@"set Photo URL succeeded."];
        }
        [self hideSpinner:^{
          [self showTypicalUIForUserUpdateResultsWithTitle:kSetPhotoURLText error:error];
        }];
      }];
    }];
  }];
}

/** @fn reloadUser
    @brief Reloads the user from server.
 */
- (void)reloadUser {
  [self showSpinner:^() {
    [[self user] reloadWithCompletion:^(NSError *_Nullable error) {
      if (error) {
        [self logFailure:@"reload user failed" error:error];
      } else {
        [self logSuccess:@"reload user succeeded."];
      }
      [self hideSpinner:^() {
        [self showTypicalUIForUserUpdateResultsWithTitle:kReloadText error:error];
      }];
    }];
  }];
}

/** @fn linkWithAuthProvider:retrieveData:
    @brief Asks the user to sign in with an auth provider and link the current user with it.
    @param authProvider The auth provider to sign in and link with.
    @param retrieveData Defines if additional provider data should be read.
 */
- (void)linkWithAuthProvider:(id<AuthProvider>)authProvider retrieveData:(BOOL)retrieveData {
  FIRUser *user = [self user];
  if (!user) {
    return;
  }
  [authProvider getAuthCredentialWithPresentingViewController:self
                                                     callback:^(FIRAuthCredential *credential,
                                                                NSError *error) {
    if (credential) {
      FIRAuthDataResultCallback completion = ^(FIRAuthDataResult *_Nullable authResult,
                                               NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"link auth provider failed" error:error];
        } else {
          [self logSuccess:@"link auth provider succeeded."];
        }
        if (authResult.additionalUserInfo) {
          [self logSuccess:[self stringWithAdditionalUserInfo:authResult.additionalUserInfo]];
        }
        if (retrieveData) {
          [self showUIForAuthDataResultWithResult:authResult error:error];
        } else {
          [self showTypicalUIForUserUpdateResultsWithTitle:@"Link Account" error:error];
        }
      };
      FIRAuthResultCallback callback = ^(FIRUser *_Nullable user,
                                         NSError *_Nullable error) {
        completion(nil, error);
      };
      if (retrieveData) {
        [user linkAndRetrieveDataWithCredential:credential completion:completion];
      } else {
        [user linkWithCredential:credential completion:callback];
      }
    }
  }];
}

/** @fn linkWithGoogle
    @brief Asks the user to sign in with Google and link the current user with this Google account.
 */
- (void)linkWithGoogle {
  [self linkWithAuthProvider:[AuthProviders google] retrieveData:NO];
}

/** @fn linkWithGoogleAndRetrieveData
    @brief Asks the user to sign in with Google and link the current user with this Google account
        and retrieve additional data.
 */
- (void)linkWithGoogleAndRetrieveData {
  [self linkWithAuthProvider:[AuthProviders google] retrieveData:YES];
}

/** @fn linkWithFacebook
    @brief Asks the user to sign in with Facebook and link the current user with this Facebook
        account.
 */
- (void)linkWithFacebook {
  [self linkWithAuthProvider:[AuthProviders facebook] retrieveData:NO];
}

/** @fn linkWithFacebookAndRetrieveData
    @brief Asks the user to sign in with Facebook and link the current user with this Facebook
        account and retrieve additional data.
 */
- (void)linkWithFacebookAndRetrieveData {
  [self linkWithAuthProvider:[AuthProviders facebook] retrieveData:YES];
}

/** @fn linkWithEmailPassword
    @brief Asks the user to sign in with Facebook and link the current user with this Facebook
        account.
 */
- (void)linkWithEmailPassword {
  [self showEmailPasswordDialogWithCompletion:^(FIRAuthCredential *credential) {
    [self showSpinner:^{
      [[self user] linkWithCredential:credential
                           completion:^(FIRUser *user, NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"link Email/Password failed" error:error];
        } else {
          [self logSuccess:@"link Email/Password succeeded."];
        }
        [self hideSpinner:^{
          [self showTypicalUIForUserUpdateResultsWithTitle:kLinkWithEmailPasswordText error:error];
        }];
      }];
    }];
  }];
}

/** @fn showEmailPasswordDialogWithCompletion:
    @brief shows email/password input dialog.
    @param completion The completion block that will do some operation on the credential email
        /passwowrd credential obtained.
 */
- (void)showEmailPasswordDialogWithCompletion:(ShowEmailPasswordDialogCompletion)completion {
  [self showTextInputPromptWithMessage:@"Email Address:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
    if (!userPressedOK || !email.length) {
      return;
    }
    [self showTextInputPromptWithMessage:@"Password:"
                         completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
      if (!userPressedOK || !password.length) {
        return;
      }

      FIRAuthCredential *credential = [FIREmailAuthProvider credentialWithEmail:email
                                                                       password:password];
      completion(credential);
    }];
  }];
}

/** @fn unlinkFromProvider:
    @brief Unlinks the current user from the provider with the specified provider ID.
    @param provider The provider ID of the provider to unlink the current user's account from.
    @completion A completion block to be executed after the provider is unlinked.
 */
- (void)unlinkFromProvider:(NSString *)provider
                completion:(void(^)(NSError *_Nullable))completion {
  [[self user] unlinkFromProvider:provider
                       completion:^(FIRUser *_Nullable user,
                                    NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"unlink auth provider failed" error:error];
      completion(error);
    } else {
      [self logSuccess:@"unlink auth provider succeeded."];
      if (completion) {
        completion(nil);
      }
    }
    [self showTypicalUIForUserUpdateResultsWithTitle:kUnlinkTitle error:error];
  }];
}

/** @fn getProvidersForEmail
    @brief Prompts the user for an email address, calls @c FIRAuth.getProvidersForEmail:callback:
        and displays the result.
 */
- (void)getProvidersForEmail {
  [self showTextInputPromptWithMessage:@"Email:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }

    [self showSpinner:^{
      [[AppManager auth] fetchProvidersForEmail:userInput
                                     completion:^(NSArray<NSString *> *_Nullable providers,
                                                  NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"get providers for email failed" error:error];
        } else {
          [self logSuccess:@"get providers for email succeeded."];
        }
        [self hideSpinner:^{
          if (error) {
            [self showMessagePrompt:error.localizedDescription];
            return;
          }

          [self showMessagePrompt:[providers componentsJoinedByString:@", "]];
        }];
      }];
    }];
  }];
}

/** @fn actionCodeRequestTypeString
    @brief Returns a string description for the type of the next action code request.
 */
- (NSString *)actionCodeRequestTypeString {
  switch (_actionCodeRequestType) {
    case ActionCodeRequestTypeInApp:
      return @"In-App + Continue URL";
    case ActionCodeRequestTypeContinue:
      return @"Continue URL";
    case ActionCodeRequestTypeEmail:
      return @"Email Only";
  }
}

/** @fn toggleActionCodeRequestType
    @brief Toggle the next action code request type.
 */
- (void)toggleActionCodeRequestType {
  switch (_actionCodeRequestType) {
    case ActionCodeRequestTypeInApp:
      _actionCodeRequestType = ActionCodeRequestTypeContinue;
      break;
    case ActionCodeRequestTypeContinue:
      _actionCodeRequestType = ActionCodeRequestTypeEmail;
      break;
    case ActionCodeRequestTypeEmail:
      _actionCodeRequestType = ActionCodeRequestTypeInApp;
      break;
  }
  [self updateTable];
}

- (void)changeActionCodeContinueURL {
  [self showTextInputPromptWithMessage:kContinueURLDescription
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (userPressedOK) {
      _actionCodeContinueURL = userInput.length ? [NSURL URLWithString:userInput] : nil;
      [self updateTable];
    }
  }];
}

/** @fn requestVerifyEmail
    @brief Requests a "verify email" email be sent.
 */
- (void)requestVerifyEmail {
  [self showSpinner:^{
    void (^sendEmailVerification)(void (^)(NSError *)) = ^(void (^completion)(NSError *)) {
      if (_actionCodeRequestType == ActionCodeRequestTypeEmail) {
        [[self user] sendEmailVerificationWithCompletion:completion];
      } else {
        [[self user] sendEmailVerificationWithActionCodeSettings:[self actionCodeSettings]
                                                      completion:completion];
      }
    };
    sendEmailVerification(^(NSError *_Nullable error) {
      [self hideSpinner:^{
        if (error) {
          [self logFailure:@"request verify email failed" error:error];
          [self showMessagePrompt:error.localizedDescription];
          return;
        }
        [self logSuccess:@"request verify email succeeded."];
        [self showMessagePrompt:@"Sent"];
      }];
    });
  }];
}

/** @fn requestPasswordReset
    @brief Requests a "password reset" email be sent.
 */
- (void)requestPasswordReset {
  [self showTextInputPromptWithMessage:@"Email:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }
    [self showSpinner:^{
      void (^requestPasswordReset)(void (^)(NSError *)) = ^(void (^completion)(NSError *)) {
        if (_actionCodeRequestType == ActionCodeRequestTypeEmail) {
          [[AppManager auth] sendPasswordResetWithEmail:userInput completion:completion];
        } else {
          [[AppManager auth] sendPasswordResetWithEmail:userInput
                                     actionCodeSettings:[self actionCodeSettings]
                                             completion:completion];
        }
      };
      requestPasswordReset(^(NSError *_Nullable error) {
        [self hideSpinner:^{
          if (error) {
            [self logFailure:@"request password reset failed" error:error];
            [self showMessagePrompt:error.localizedDescription];
            return;
          }
          [self logSuccess:@"request password reset succeeded."];
          [self showMessagePrompt:@"Sent"];
        }];
      });
    }];
  }];
}

/** @fn resetPassword
    @brief Performs a password reset operation.
 */
- (void)resetPassword {
  [self showTextInputPromptWithMessage:@"OOB Code:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }
    NSString *code =  userInput;

    [self showTextInputPromptWithMessage:@"New Password:"
                         completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
      if (!userPressedOK || !userInput.length) {
        return;
      }

      [self showSpinner:^{
        [[AppManager auth] confirmPasswordResetWithCode:code
                                            newPassword:userInput
                                             completion:^(NSError *_Nullable error) {
          [self hideSpinner:^{
            if (error) {
              [self logFailure:@"Password reset failed" error:error];
              [self showMessagePrompt:error.localizedDescription];
              return;
            }
            [self logSuccess:@"Password reset succeeded."];
            [self showMessagePrompt:@"Password reset succeeded."];
          }];
        }];
      }];
    }];
  }];
}

/** @fn checkActionCode
    @brief Performs a "check action code" operation.
 */
- (void)checkActionCode {
  [self showTextInputPromptWithMessage:@"OOB Code:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }
    [self showSpinner:^{
      [[AppManager auth] checkActionCode:userInput completion:^(FIRActionCodeInfo *_Nullable info,
                                                                NSError *_Nullable error) {
        [self hideSpinner:^{
          if (error) {
            [self logFailure:@"Check action code failed" error:error];
            [self showMessagePrompt:error.localizedDescription];
            return;
          }
          [self logSuccess:@"Check action code succeeded."];
          NSString *email = [info dataForKey:FIRActionCodeEmailKey];
          NSString *fromEmail = [info dataForKey:FIRActionCodeFromEmailKey];
          NSString *message =
              fromEmail ? [NSString stringWithFormat:@"%@ -> %@", fromEmail, email] : email;
          NSString *operation = [self nameForActionCodeOperation:info.operation];
          [self showMessagePromptWithTitle:operation
                                   message:message
                          showCancelButton:NO
                                completion:nil];
        }];
      }];
    }];
  }];
}

/** @fn applyActionCode
    @brief Performs a "apply action code" operation.
 */
- (void)applyActionCode {
  [self showTextInputPromptWithMessage:@"OOB Code:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }
    [self showSpinner:^{

      [[AppManager auth] applyActionCode:userInput completion:^(NSError *_Nullable error) {
        [self hideSpinner:^{
          if (error) {
            [self logFailure:@"Apply action code failed" error:error];
            [self showMessagePrompt:error.localizedDescription];
            return;
          }
          [self logSuccess:@"Apply action code succeeded."];
          [self showMessagePrompt:@"Action code was properly applied."];
        }];
      }];
    }];
  }];
}

/** @fn verifyPasswordResetCode
    @brief Performs a "verify password reset code" operation.
 */
- (void)verifyPasswordResetCode {
  [self showTextInputPromptWithMessage:@"OOB Code:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }
    [self showSpinner:^{
      [[AppManager auth] verifyPasswordResetCode:userInput completion:^(NSString *_Nullable email,
                                                                        NSError *_Nullable error) {
        [self hideSpinner:^{
          if (error) {
            [self logFailure:@"Verify password reset code failed" error:error];
            [self showMessagePrompt:error.localizedDescription];
            return;
          }
          [self logSuccess:@"Verify password resest code succeeded."];
          NSString *alertMessage =
            [[NSString alloc] initWithFormat:@"Code verified for email: %@", email];
          [self showMessagePrompt:alertMessage];
        }];
      }];
    }];
  }];
}


/** @fn nameForActionCodeOperation
    @brief Returns the string value of the provided FIRActionCodeOperation value.
    @param operation the FIRActionCodeOperation value to convert to string.
    @return String conversion of FIRActionCodeOperation value.
 */
- (NSString *)nameForActionCodeOperation:(FIRActionCodeOperation)operation {
  switch (operation) {
  case FIRActionCodeOperationVerifyEmail:
    return @"Verify Email";
  case FIRActionCodeOperationRecoverEmail:
    return @"Recover Email";
  case FIRActionCodeOperationPasswordReset:
    return @"Password Reset";
  case FIRActionCodeOperationUnknown:
    return @"Unknown action";
  }
}

/** @fn updateEmail
    @brief Changes the email address of the current user.
 */
- (void)updateEmail {
  [self showTextInputPromptWithMessage:@"Email Address:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK || !userInput.length) {
      return;
    }

    [self showSpinner:^{
      [[self user] updateEmail:userInput completion:^(NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"update email failed" error:error];
        } else {
          [self logSuccess:@"update email succeeded."];
        }
        [self hideSpinner:^{
          [self showTypicalUIForUserUpdateResultsWithTitle:kUpdateEmailText error:error];
        }];
      }];
    }];
  }];
}

/** @fn updatePassword
    @brief Updates the password of the current user.
 */
- (void)updatePassword {
  [self showTextInputPromptWithMessage:@"New Password:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
    if (!userPressedOK) {
      return;
    }

    [self showSpinner:^{
      [[self user] updatePassword:userInput completion:^(NSError *_Nullable error) {
        if (error) {
          [self logFailure:@"update password failed" error:error];
        } else {
          [self logSuccess:@"update password succeeded."];
        }
        [self hideSpinner:^{
          [self showTypicalUIForUserUpdateResultsWithTitle:kUpdatePasswordText error:error];
        }];
      }];
    }];
  }];
}

/** @fn createUser
    @brief Creates a new user.
 */
- (void)createUser {
  [self showTextInputPromptWithMessage:@"Email:"
                          keyboardType:UIKeyboardTypeEmailAddress
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
    if (!userPressedOK || !email.length) {
      return;
    }

    [self showTextInputPromptWithMessage:@"Password:"
                         completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
      if (!userPressedOK) {
        return;
      }

      [self showSpinner:^{
        [[AppManager auth] createUserWithEmail:email
                                      password:password
                                    completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
          if (error) {
            [self logFailure:@"create user failed" error:error];
          } else {
            [self logSuccess:@"create user succeeded."];
          }
          [self hideSpinner:^{
            [self showTypicalUIForUserUpdateResultsWithTitle:kCreateUserTitle error:error];
          }];
        }];
      }];
    }];
  }];
}

/** @fn createUserAuthDataResult
    @brief Creates a new user.
 */
- (void)createUserAuthDataResult {
  [self showTextInputPromptWithMessage:@"Email:"
                          keyboardType:UIKeyboardTypeEmailAddress
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
    if (!userPressedOK || !email.length) {
      return;
    }

    [self showTextInputPromptWithMessage:@"Password:"
                         completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
      if (!userPressedOK) {
        return;
      }

      [self showSpinner:^{
        [[AppManager auth] createUserAndRetrieveDataWithEmail:email
                                                     password:password
                                                   completion:^(FIRAuthDataResult *_Nullable result,
                                                                NSError *_Nullable error) {
          if (error) {
            [self logFailure:@"create user failed" error:error];
          } else {
            [self logSuccess:@"create user succeeded."];
            [self log:result.user.uid];
          }
          [self hideSpinner:^{
            [self showTypicalUIForUserUpdateResultsWithTitle:kCreateUserTitle error:error];
          }];
        }];
      }];
    }];
  }];
}

/** @fn signInWithPhoneNumber
    @brief Allows sign in with phone number.
 */
- (void)signInWithPhoneNumber {
  [self commonPhoneNumberInputWithTitle:@"Phone #" Completion:^(NSString *_Nullable phone) {
    [self showSpinner:^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
      [[AppManager phoneAuthProvider] verifyPhoneNumber:phone
                                             completion:^(NSString *_Nullable verificationID,
                                                          NSError *_Nullable error) {
#pragma clang diagnostic pop
        [self hideSpinner:^{
          if (error) {
            [self logFailure:@"failed to send verification code" error:error];
            [self showMessagePrompt:error.localizedDescription];
            return;
          }
          [self logSuccess:@"Code sent"];

          [self commonPhoneNumberInputWithTitle:@"Code"
                                     Completion:^(NSString *_Nullable verificationCode) {
            [self commontPhoneVerificationWithVerificationID:verificationID
                                            verificationCode:verificationCode];
          }];
        }];
      }];
    }];
  }];
}

/** @fn signInWithPhoneNumber
    @brief Allows sign in with phone number using reCAPTCHA.
    @param phoneNumber Number pass in string.
    @completion A completion block to be executed after successful phone number sign in.
 */
- (void)signInWithPhoneNumber:(NSString *_Nullable)phoneNumber
                   completion:(void(^)(NSError *_Nullable))completion {
  [self showSpinner:^{
    [[AppManager phoneAuthProvider] verifyPhoneNumber:phoneNumber
                                           UIDelegate:nil
                                           completion:^(NSString *_Nullable verificationID,
                                                        NSError *_Nullable error) {
      [self hideSpinner:^{
        if (error) {
          [self logFailure:@"failed to send verification code" error:error];
          [self showMessagePrompt:error.localizedDescription];
          if (completion) {
            completion(error);
          }
          return;
        }
        [self logSuccess:@"Code sent"];
        [self commonPhoneNumberInputWithTitle:@"Code"
                                   Completion:^(NSString *_Nullable verificationCode) {
         [self commontPhoneVerificationWithVerificationID:verificationID
                                         verificationCode:verificationCode];
          if (completion) {
            completion(nil);
          }
        }];
      }];
    }];
  }];
}

/** @fn signInWithPhoneNumberWithPrompt
    @brief Allows sign in with phone number via popup prompt.
 */
- (void)signInWithPhoneNumberWithPrompt {
  [self commonPhoneNumberInputWithTitle:@"Phone #"
                             Completion:^(NSString *_Nullable phone) {
    [self signInWithPhoneNumber:phone completion:nil];
  }];
}

/** @fn commonPhoneNumberInputWithLabel:Completion
    @brief Allows user input into a text field.
    @param title of the promt.
 */
- (void)commonPhoneNumberInputWithTitle:(NSString *)title
                             Completion:(textInputCompletionBlock)completion {
  [self showTextInputPromptWithMessage:title
                          keyboardType:UIKeyboardTypePhonePad
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable phoneNumber) {
    if (!userPressedOK) {
      return;
    }
    completion(phoneNumber);
  }];
}
/** @fn commonPhoneNumberInputWithLabel:Completion
    @brief Finishes the phone number verification flow.
    @param verificationID The verificationID from the backend.
    @param verificationCode The verificationCode from the SMS message.
 */
- (void)commontPhoneVerificationWithVerificationID:(NSString *)verificationID
                                  verificationCode:(NSString *)verificationCode {
  [self showSpinner:^{
    FIRAuthCredential *credential =
        [[AppManager phoneAuthProvider] credentialWithVerificationID:verificationID
                                                    verificationCode:verificationCode];
    [[AppManager auth] signInWithCredential:credential
                                 completion:^(FIRUser *_Nullable user,
                                              NSError *_Nullable error) {
      [self hideSpinner:^{
        if (error) {
          [self logFailure:@"failed to verify phone number" error:error];
          [self showMessagePrompt:error.localizedDescription];
          return;
        }
      }];
    }];
  }];
}

/** @fn updatePhoneNumber
    @brief Allows adding a verified phone number to the currently signed user.
    @param phoneNumber Number pass in string.
    @completion A completion block to be executed after phone number is updated.
 */
- (void)updatePhoneNumber:(NSString *_Nullable)phoneNumber
               completion:(void(^)(NSError *_Nullable))completion{
  [self showSpinner:^{
    [[AppManager phoneAuthProvider] verifyPhoneNumber:phoneNumber
                                           UIDelegate:nil
                                           completion:^(NSString *_Nullable verificationID,
                                                         NSError *_Nullable error) {
     if (error) {
       [self logFailure:@"failed to send verification code" error:error];
       [self showMessagePrompt:error.localizedDescription];
       completion(error);
       return;
     }
     [self logSuccess:@"Code sent"];

     [self showTextInputPromptWithMessage:@"Verification code:"
                             keyboardType:UIKeyboardTypeNumberPad
                          completionBlock:^(BOOL userPressedOK,
                                            NSString *_Nullable verificationCode) {
       if (!userPressedOK || !verificationCode.length) {
         return;
       }
       [self showSpinner:^{
         FIRPhoneAuthCredential *credential =
         [[AppManager phoneAuthProvider] credentialWithVerificationID:verificationID
                                                     verificationCode:verificationCode];
         [[self user] updatePhoneNumberCredential:credential
                                       completion:^(NSError *_Nullable error) {
           if (error) {
             [self logFailure:@"update phone number failed" error:error];
             [self showMessagePrompt:error.localizedDescription];
             completion(error);
           } else {
             [self logSuccess:@"update phone number succeeded."];
             if (completion) {
               completion(nil);
             }
           }
        }];
      }];
    }];
    [self hideSpinner:^{
      [self showTypicalUIForUserUpdateResultsWithTitle:kCreateUserTitle error:error];
   }];
  }];
 }];
}

/** @fn updatePhoneNumberWithPrompt
    @brief Allows adding a verified phone number to the currently signed user via popup prompt.
 */
- (void)updatePhoneNumberWithPrompt {
  [self showTextInputPromptWithMessage:@"Update Phone #:"
                          keyboardType:UIKeyboardTypePhonePad
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable phoneNumber) {
    if (!userPressedOK || !phoneNumber.length) {
      return;
    }
    [self updatePhoneNumber:phoneNumber completion:nil];
 }];
}

/** @fn linkPhoneNumber
    @brief Allows linking a verified phone number to the currently signed user.
    @param phoneNumber Number pass in string.
    @completion A completion block to be executed after linking phone number.
 */
- (void)linkPhoneNumber:(NSString *_Nullable)phoneNumber
             completion:(void(^)(NSError *_Nullable))completion{
    [self showSpinner:^{
    [[AppManager phoneAuthProvider] verifyPhoneNumber:phoneNumber
                                           UIDelegate:nil
                                           completion:^(NSString *_Nullable verificationID,
                                                        NSError *_Nullable error) {
      [self hideSpinner:^{
        if (error) {
          [self logFailure:@"failed to send verification code" error:error];
          [self showMessagePrompt:error.localizedDescription];
          completion(error);
          return;
        }
        [self logSuccess:@"Code sent"];

        [self showTextInputPromptWithMessage:@"Verification code:"
                                keyboardType:UIKeyboardTypeNumberPad
                             completionBlock:^(BOOL userPressedOK,
                                               NSString *_Nullable verificationCode) {
          if (!userPressedOK || !verificationCode.length) {
            return;
          }
          [self showSpinner:^{
            FIRPhoneAuthCredential *credential =
                [[AppManager phoneAuthProvider] credentialWithVerificationID:verificationID
                                                            verificationCode:verificationCode];
            [[self user] linkWithCredential:credential
                                 completion:^(FIRUser *_Nullable user,
                                              NSError *_Nullable error) {
              [self hideSpinner:^{
                if (error) {
                  if (error.code == FIRAuthErrorCodeCredentialAlreadyInUse) {
                    [self showMessagePromptWithTitle:@"Phone number is already linked to "
                                                     @"another user"
                                             message:@"Tap Ok to sign in with that user now."
                                    showCancelButton:YES
                                          completion:^(BOOL userPressedOK,
                                                       NSString *_Nullable userInput) {
                      if (userPressedOK) {
                        // If FIRAuthErrorCodeCredentialAlreadyInUse error, sign in with the
                        // provided credential.
                        [self showSpinner:^{
                          FIRPhoneAuthCredential *credential =
                              error.userInfo[FIRAuthUpdatedCredentialKey];
                          [[AppManager auth] signInWithCredential:credential
                                                       completion:^(FIRUser *_Nullable user,
                                                                    NSError *_Nullable error) {
                            [self hideSpinner:^{
                              if (error) {
                                [self logFailure:@"failed to verify phone number" error:error];
                                [self showMessagePrompt:error.localizedDescription];
                                completion(error);
                                return;
                              }
                            }];
                          }];
                        }];
                      }
                    }];
                  } else {
                    [self logFailure:@"link phone number failed" error:error];
                    [self showMessagePrompt:error.localizedDescription];
                  }
                  return;
                }
                [self logSuccess:@"link phone number succeeded."];
                if (completion) {
                  completion(nil);
                }
              }];
            }];
          }];
        }];
      }];
    }];
  }];
}

/** @fn linkPhoneNumberWithPrompt
    @brief Allows linking a verified phone number to the currently signed user via popup prompt.
 */
- (void)linkPhoneNumberWithPrompt {
  [self showTextInputPromptWithMessage:@"Phone #:"
                          keyboardType:UIKeyboardTypePhonePad
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable phoneNumber) {
    if (!userPressedOK || !phoneNumber.length) {
      return;
    }
    [self linkPhoneNumber:phoneNumber completion:nil];
  }];
}

/** @fn signInAnonymously
    @brief Signs in as an anonymous user.
 */
- (void)signInAnonymously {
  [[AppManager auth] signInAnonymouslyWithCompletion:^(FIRUser *_Nullable user,
                                                       NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"sign-in anonymously failed" error:error];
    } else {
      [self logSuccess:@"sign-in anonymously succeeded."];
    }
    [self showTypicalUIForUserUpdateResultsWithTitle:kSignInAnonymouslyButtonText error:error];
  }];
}

/** @fn signInAnonymouslyAuthDataResult
    @brief Signs in as an anonymous user, receiving an auth result containing a signed in user upon
        success.
 */
- (void)signInAnonymouslyAuthDataResult {
  [[AppManager auth] signInAnonymouslyAndRetrieveDataWithCompletion:
      ^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"sign-in anonymously failed" error:error];
    } else {
      [self logSuccess:@"sign-in anonymously succeeded."];
      [self log:[NSString stringWithFormat:@"User ID : %@", authResult.user.uid]];
    }
    [self showTypicalUIForUserUpdateResultsWithTitle:kSignInAnonymouslyButtonText error:error];
  }];
}

/** @fn signInWithGitHub
    @brief Signs in as a GitHub user. Prompts the user for an access token and uses this access
        token to create a GitHub (generic) credential for signing in.
 */
- (void)signInWithGitHub {
  [self showTextInputPromptWithMessage:@"GitHub Access Token:"
                       completionBlock:^(BOOL userPressedOK, NSString *_Nullable accessToken) {
    if (!userPressedOK || !accessToken.length) {
      return;
    }
    FIRAuthCredential *credential =
        [FIROAuthProvider credentialWithProviderID:FIRGitHubAuthProviderID accessToken:accessToken];
    if (credential) {
        [[AppManager auth] signInWithCredential:credential completion:^(FIRUser *_Nullable user,
                                                                        NSError *_Nullable error) {
          if (error) {
            [self logFailure:@"sign-in with provider failed" error:error];
          } else {
            [self logSuccess:@"sign-in with provider succeeded."];
          }
          [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In" error:error];
      }];
    }
  }];
}

/** @fn deleteApp
    @brief Deletes the @c FIRApp associated with our @c FIRAuth instance.
 */
- (void)deleteApp {
  [[FIRApp defaultApp] deleteApp:^(BOOL success) {
    [self log:success ? @"App deleted successfully." : @"Failed to delete app."];
  }];
}

/** @fn timeAuthInitialization
    @brief Times FIRAuth instance initialization time.
 */
- (void)timeAuthInitialization {
  // Temporarily disable auth state listener to avoid interfering with the result.
  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                  name:FIRAuthStateDidChangeNotification
                                                object:nil];
  [self showSpinner:^() {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^() {
      const int numberOfRuns = 4096;
      FIRApp *app = [FIRApp defaultApp];
      NSString *key = NSStringFromClass([FIRAuth class]);
      NSDate *startTime = [NSDate date];
      for (int i = 0; i < numberOfRuns; i++) {
        @autoreleasepool {
          [FIRAppAssociationRegistration deregisterObjectWithHost:app key:key];
          [FIRAuth auth];
        }
      }
      NSDate *endTime = [NSDate date];
      dispatch_async(dispatch_get_main_queue(), ^() {
        // Re-enable auth state listener.
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(authStateChangedForAuth:)
                                                     name:FIRAuthStateDidChangeNotification
                                                   object:nil];
        [self hideSpinner:^() {
          NSTimeInterval averageTime = [endTime timeIntervalSinceDate:startTime] / numberOfRuns;
          NSString *message = [NSString stringWithFormat:
              @"Each [FIRAuth auth] takes average of %.3f ms for %d runs",
              averageTime * 1000, numberOfRuns];
          [self showMessagePromptWithTitle:@"Timing Result"
                                   message:message
                          showCancelButton:NO
                                completion:nil];
        }];
      });
    });
  }];
}

#pragma mark - Helpers

/** @fn user
    @brief The user to use for user operations. Takes into account the "use signed-in user vs. use
        user in memory" setting.
 */
- (FIRUser *)user {
  return _useUserInMemory ? _userInMemory : [AppManager auth].currentUser;
}

/** @fn actionCodeSettings
    @brief Returns the action code settings for this app.
 */
- (FIRActionCodeSettings *)actionCodeSettings {
  FIRActionCodeSettings *actionCodeSettings = [[FIRActionCodeSettings alloc] init];
  actionCodeSettings.URL = _actionCodeContinueURL;
  actionCodeSettings.handleCodeInApp = _actionCodeRequestType == ActionCodeRequestTypeInApp;
  return actionCodeSettings;
}

/** @fn stringWithAdditionalUserInfo:
    @brief Gets the string description of the additional user info.
    @param additionalUserInfo The additional user info in question.
    @return A string to description the additional user info.
 */
- (NSString *)stringWithAdditionalUserInfo:(nullable FIRAdditionalUserInfo *)additionalUserInfo {
  if (!additionalUserInfo) {
    return @"(no additional user info)";
  }
  NSString *newUserString = additionalUserInfo.isNewUser ? @"new user" : @"existing user";
  return [NSString stringWithFormat:@"%@: %@", newUserString, additionalUserInfo.profile];
}

/** @fn showTypicalUIForUserUpdateResultsWithTitle:error:
    @brief Shows a prompt if error is non-nil with the localized description of the error.
    @param resultsTitle The title of the prompt
    @param error The error details to display if non-nil.
 */
- (void)showTypicalUIForUserUpdateResultsWithTitle:(NSString *)resultsTitle
                                             error:(NSError *)error {
  if (error) {
    NSString *message = [NSString stringWithFormat:@"%@ (%ld)\n%@",
                                                   error.domain,
                                                   (long)error.code,
                                                   error.localizedDescription];
    if (error.code == FIRAuthErrorCodeAccountExistsWithDifferentCredential) {
      NSString *errorEmail = error.userInfo[FIRAuthErrorUserInfoEmailKey];
      resultsTitle = [NSString stringWithFormat:@"Existing email : %@", errorEmail];
    }
    [self showMessagePromptWithTitle:resultsTitle
                             message:message
                    showCancelButton:NO
                          completion:nil];
    return;
  }
  [self updateUserInfo];
}

/** @fn showUIForAuthDataResultWithResult:error:
    @brief Shows a prompt if error is non-nil with the localized description of the error.
    @param result The auth data result if non-nil.
    @param error The error details to display if non-nil.
 */
- (void)showUIForAuthDataResultWithResult:(FIRAuthDataResult *)result
                                    error:(NSError *)error {
  NSString *errorMessage = [NSString stringWithFormat:@"%@ (%ld)\n%@",
                                                      error.domain ?: @"",
                                                      (long)error.code,
                                                      error.localizedDescription ?: @""];
  [self showMessagePromptWithTitle:@"Error"
                           message:errorMessage
                  showCancelButton:NO
                        completion:^(BOOL userPressedOK,
                                     NSString *_Nullable userInput) {
    [self showMessagePromptWithTitle:@"Profile Info"
                             message:[self stringWithAdditionalUserInfo:result.additionalUserInfo]
                    showCancelButton:NO
                          completion:nil];
    [self updateUserInfo];
  }];
}

- (void)doSignInWithCustomToken:(NSString *_Nullable)userEnteredTokenText {
  [[AppManager auth] signInWithCustomToken:userEnteredTokenText
                                completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
    if (error) {
      [self logFailure:@"sign-in with custom token failed" error:error];
      [self showMessagePromptWithTitle:kSignInErrorAlertTitle
                               message:error.localizedDescription
                      showCancelButton:NO
                            completion:nil];
      return;
    }
    [self logSuccess:@"sign-in with custom token succeeded."];
    [self showMessagePromptWithTitle:kSignedInAlertTitle
                             message:user.displayName
                    showCancelButton:NO
                          completion:nil];
  }];
}

- (void)updateUserInfo {
  [_userInfoTableViewCell updateContentsWithUser:[AppManager auth].currentUser];
  [_userInMemoryInfoTableViewCell updateContentsWithUser:_userInMemory];
}

- (void)authStateChangedForAuth:(NSNotification *)notification {
  [self updateUserInfo];
  if (notification) {
    [self log:[NSString stringWithFormat:
       @"received FIRAuthStateDidChange notification on user '%@'.",
       ((FIRAuth *)notification.object).currentUser.uid]];
  }
}

/** @fn clearConsole
    @brief Clears the console text.
 */
- (IBAction)clearConsole:(id)sender {
  [_consoleString appendString:@"\n\n"];
  _consoleTextView.text = @"";
}

/** @fn copyConsole
    @brief Copies the current console string to the clipboard.
 */
- (IBAction)copyConsole:(id)sender {
  UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  pasteboard.string = _consoleString ?: @"";
}

@end