TapUIRoomListViewController.m 74.8 KB
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
//
//  TapUIRoomListViewController.m
//  TapTalk
//
//  Created by Dominic Vedericho on 6/9/18.
//  Copyright © 2018 Moselo. All rights reserved.
//

#import "TapUIRoomListViewController.h"
#import "TAPRoomListView.h"
#import "TAPAddNewChatViewController.h"
#import "TapUIChatViewController.h"
#import "TAPSetupRoomListView.h"
#import "TAPRoomListTableViewCell.h"
#import "TAPRoomListModel.h"
#import "TAPConnectionStatusViewController.h"
#import "TAPSearchViewController.h"
#import "TAPMyAccountViewController.h"

#import <AFNetworking/AFNetworking.h>

@interface TapUIRoomListViewController () <UITableViewDelegate, UITableViewDataSource, TAPChatManagerDelegate, UITextFieldDelegate, TAPConnectionStatusViewControllerDelegate, TAPAddNewChatViewControllerDelegate, TAPChatViewControllerDelegate, UIViewControllerPreviewingDelegate, TAPSearchViewControllerDelegate, TAPMyAccountViewControllerDelegate, UIAdaptivePresentationControllerDelegate>
@property (strong, nonatomic) UIImage *navigationShadowImage;

@property (strong, nonatomic) TAPRoomListView *roomListView;
@property (strong, nonatomic) TAPSetupRoomListView *setupRoomListView;
@property (strong, nonatomic) TAPConnectionStatusViewController *connectionStatusViewController;
@property (strong, nonatomic) TAPSearchBarView *searchBarView;
@property (strong, nonatomic) TAPImageView *profileImageView;
@property (strong, nonatomic) UIView *leftBarView;
@property (strong, nonatomic) UIView *leftBarInitialNameView;
@property (strong, nonatomic) UILabel *leftBarInitialNameLabel;
@property (strong, nonatomic) UIButton *leftBarInitialNameButton;
@property (strong, nonatomic) UIButton *closeButton;
@property (strong, nonatomic) UIButton *myAccountButton;
@property (strong, nonatomic) UIButton *rightBarButton;
@property (strong, nonatomic) NSMutableArray *unreadRoomIDs;

@property (strong, nonatomic) NSMutableDictionary *unreadMentionDictionary;

@property (nonatomic) NSInteger firstUnreadProcessCount;
@property (nonatomic) NSInteger firstUnreadTotalCount;
@property (strong, nonatomic) NSString *readUnreadStateString;
@property (strong, nonatomic) UIImage *readUnreadStateImage;

@property (nonatomic) BOOL isNeedRefreshOnNetworkDown;
@property (nonatomic) BOOL isShowMyAccountView;

- (void)mappingMessageArrayToRoomListArrayAndDictionary:(NSArray *)messageArray;
- (void)insertRoomListToArrayAndDictionary:(TAPRoomListModel *)roomList atIndex:(NSInteger)index;
- (void)runFullRefreshSequence;
- (void)fetchDataFromAPI;
- (void)insertReloadMessageAndUpdateUILogicWithMessageArray:(NSArray *)messageArray;
- (void)reloadLocalDataAndUpdateUILogicAnimated:(BOOL)animated;
- (void)refreshViewAndQueryUnreadLogicWithMessageArray:(NSArray *)messageArray animateReloadData:(BOOL)animateReloadData;
- (void)queryNumberOfUnreadMessageInRoomListArrayInBackgroundAndUpdateUIAndReloadTableView:(BOOL)reloadTableView;
- (void)processMessageFromSocket:(TAPMessageModel *)message isNewMessage:(BOOL)isNewMessage;
- (void)updateCellDataAtIndexPath:(NSIndexPath *)indexPath updateUnreadBubble:(BOOL)updateUnreadBubble;
- (void)openNewChatViewController;
- (void)hideSetupViewWithDelay:(double)delayTime;
- (void)getAndUpdateNumberOfUnreadToDelegate;
- (void)checkUpdatedUserProfileWithMessage:(TAPMessageModel *)message;
- (void)checkAndUpdateActiveUserProfile;

@end

@implementation TapUIRoomListViewController
#pragma mark - Lifecycle
- (void)loadView {
    [super loadView];
    BOOL isShowCloseButton = [[TapUI sharedInstance] getCloseRoomListButtonVisibleState];
    BOOL isShowMyAccountInChatRoom = [[TapUI sharedInstance] getMyAccountButtonInRoomListViewVisibleState];
    BOOL isShowSearchBarInChatRoom = [[TapUI sharedInstance] getSearchBarInRoomListVisibleState];
    BOOL isShowNewChatButtonInChatRoom = [[TapUI sharedInstance] getNewChatButtonInRoomListVisibleState];
    if (!isShowCloseButton && !isShowMyAccountInChatRoom && !isShowSearchBarInChatRoom && !isShowNewChatButtonInChatRoom) {
        //hide navigation bar
        _roomListView = [[TAPRoomListView alloc] initWithFrame:[TAPBaseView frameWithoutNavigationBar]];
        CGFloat topBarGap = [TAPUtil currentDeviceStatusBarHeight];
        [self.roomListView setInitialYPositionOfTableView:topBarGap];
        [self.view addSubview:self.roomListView];
    }
    else {
        _roomListView = [[TAPRoomListView alloc] initWithFrame:[TAPBaseView frameWithNavigationBar]];
        [self.view addSubview:self.roomListView];
    }

    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerLoadView)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerLoadView];
    }

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityStatusChange:) name:TAP_NOTIFICATION_REACHABILITY_STATUS_CHANGED object:nil];
    
    //Add chat manager delegate
    [[TAPChatManager sharedManager] addDelegate:self];
    
    _unreadRoomIDs = [NSMutableArray array];
    
    _setupRoomListView = [[TAPSetupRoomListView alloc] initWithFrame:[TAPBaseView frameWithoutNavigationBar]];
    [self.navigationController.view addSubview:self.setupRoomListView];
    [self.navigationController.view bringSubviewToFront:self.setupRoomListView];
        
    [self.roomListView.startChatNoChatsButton addTarget:self action:@selector(openNewChatViewController) forControlEvents:UIControlEventTouchDown];
    
    
    _closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
    _myAccountButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
    _leftBarInitialNameView = [[UIView alloc] initWithFrame:CGRectMake(5.0f, 5.0f, 30.0f, 30.0f)];
    _leftBarInitialNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.leftBarInitialNameView.frame), CGRectGetHeight(self.leftBarInitialNameView.frame))];
    _leftBarInitialNameButton = [[UIButton alloc] initWithFrame:self.leftBarInitialNameView.frame];
    _profileImageView = [[TAPImageView alloc] initWithFrame:CGRectMake(5.0f, 5.0f, 30.0f, 30.0f)];
    _leftBarView = [[UIView alloc] initWithFrame:CGRectMake(
        0.0f,
        0.0f,
        CGRectGetMaxX(self.myAccountButton.frame),
        40.0f
    )];
    _rightBarButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
    _searchBarView = [[TAPSearchBarView alloc] initWithFrame:CGRectMake(
        0.0f,
        0.0f,
        CGRectGetWidth([UIScreen mainScreen].bounds) - CGRectGetWidth(self.leftBarView.frame) - CGRectGetWidth(self.rightBarButton.frame) - 36.0f,
        30.0f
    )];
    [self setUpNavigationBar];
    
    self.roomListView.roomListTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    
    if (@available(iOS 15.0, *)) {
        [self.roomListView.roomListTableView setSectionHeaderTopPadding:0.0f];
    }
    
    self.roomListView.roomListTableView.delegate = self;
    self.roomListView.roomListTableView.dataSource = self;
    self.roomListView.roomListTableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
    
    _roomListArray = [NSMutableArray array];
    _roomListDictionary = [NSMutableDictionary dictionary];
    _unreadMentionDictionary = [NSMutableDictionary dictionary];
    
    _connectionStatusViewController = [[TAPConnectionStatusViewController alloc] init];
    [self addChildViewController:self.connectionStatusViewController];
    [self.connectionStatusViewController didMoveToParentViewController:self];
    self.connectionStatusViewController.delegate = self;
    [self.roomListView addSubview:self.connectionStatusViewController.view];
    
    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerViewDidLoad)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerViewDidLoad];
    }
    
    [self.setupRoomListView.retryButton addTarget:self action:@selector(viewLoadedSequence) forControlEvents:UIControlEventTouchUpInside];
    
    //fetch pref
    self.unreadRoomIDs = [[TAPDataManager getUnreadRoomIDs] mutableCopy];
    
    //View appear sequence
    [self viewLoadedSequence];
    
    //Check for 3D Touch availability
    if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
        [self registerForPreviewingWithDelegate:self sourceView:self.roomListView.roomListTableView];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _isViewAppear = YES;
    
    //Check and update current active user profile picture
    [self checkAndUpdateActiveUserProfile];

    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerViewWillAppear)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerViewWillAppear];
    }
    
    //Check show navigation bar of not
    BOOL isShowCloseButton = [[TapUI sharedInstance] getCloseRoomListButtonVisibleState];
    BOOL isShowMyAccountInChatRoom = [[TapUI sharedInstance] getMyAccountButtonInRoomListViewVisibleState];
    BOOL isShowSearchBarInChatRoom = [[TapUI sharedInstance] getSearchBarInRoomListVisibleState];
    BOOL isShowNewChatButtonInChatRoom = [[TapUI sharedInstance] getNewChatButtonInRoomListVisibleState];
    if (!isShowCloseButton && !isShowMyAccountInChatRoom && !isShowSearchBarInChatRoom && !isShowNewChatButtonInChatRoom) {
        //Hide Navigation Bar
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    else {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    
    if ([[TapTalk sharedInstance] getTapTalkSocketConnectionMode] == TapTalkSocketConnectionModeConnectIfNeeded) {
        [[TapTalk sharedInstance] connectWithSuccess:^{
                    
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _isViewAppear = NO;
    
    if (self.searchBarView.searchTextField.isFirstResponder) {
        [self.searchBarView.searchTextField resignFirstResponder];
    }
    
    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerViewWillDisappear)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerViewWillDisappear];
    }
    
    if ([[TapTalk sharedInstance] getTapTalkSocketConnectionMode] == TapTalkSocketConnectionModeConnectIfNeeded) {
        [[TapTalk sharedInstance] disconnectWithCompletionHandler:^{
            
        }];
    }
}

- (void)dealloc {
    [[TAPChatManager sharedManager] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TAP_NOTIFICATION_REACHABILITY_STATUS_CHANGED object:nil];
    
    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerDealloc)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerDealloc];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerDidReceiveMemoryWarning)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerDidReceiveMemoryWarning];
    }
}
    
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerViewDidAppear)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerViewDidAppear];
    }
}
    
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if ([self.lifecycleDelegate respondsToSelector:@selector(TapUIRoomListViewControllerViewDidDisappear)]) {
        [self.lifecycleDelegate TapUIRoomListViewControllerViewDidDisappear];
    }
}

#pragma mark - Data Source
#pragma mark TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return [self.roomListArray count];
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 74.0f;
    }
    
    return 0.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *cellID = @"TAPRoomListTableViewCell";
        
        TAPRoomListTableViewCell *cell = [[TAPRoomListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        TAPRoomListModel *roomList = [self.roomListArray objectAtIndex:indexPath.row];
        [cell setRoomListTableViewCellWithData:roomList updateUnreadBubble:NO];
        
        if (indexPath.row == [self.roomListArray count] - 1) {
            [cell setIsLastCellSeparator:YES];
        }
        else {
            [cell setIsLastCellSeparator:NO];
        }
        
        return cell;
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] init];
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc] init];
    return footer;
}

//DV Note
//Temporary Hidden For V1 (30 Jan 2019)
//Hide Blocked Contacts
//- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
//    UITableViewRowAction *readRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        NSLog(@"Read Did Tapped");
//    }];
//    readRowAction.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TAPIconSlideActionRead" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil]];
//
//    UITableViewRowAction *muteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        NSLog(@"Mute Did Tapped");
//    }];
//    muteRowAction.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TAPIconSlideActionMute" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil]];
//
//    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        NSLog(@"Delete Did Tapped");
//    }];
//    deleteRowAction.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TAPIconSlideActionDelete" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil]];
//
//    NSArray<UITableViewRowAction *> *rowActionArray = [NSArray arrayWithObjects:deleteRowAction, muteRowAction, readRowAction, nil];
//    return rowActionArray;
//}
//END DV NOTE

#pragma mark - Delegate
#pragma mark UIViewControllerPreviewing
//- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
//    NSIndexPath *indexPath = [self.roomListView.roomListTableView indexPathForRowAtPoint:location];
//
//    TAPRoomListTableViewCell *cell = [self.roomListView.roomListTableView cellForRowAtIndexPath:indexPath];
//
//    TAPRoomListModel *selectedRoomList = [self.roomListArray objectAtIndex:indexPath.row];
//    TAPMessageModel *selectedMessage = selectedRoomList.lastMessage;
//    TAPRoomModel *room = selectedMessage.room;
//
//    CGRect convertedRect = [cell convertRect:cell.bounds toView:self.roomListView.roomListTableView];
//    previewingContext.sourceRect = convertedRect;
//
//    //DV Note - Open Room with Room method (duplicate from TapTalk Instance)
//    [[TAPChatManager sharedManager] openRoom:room];
//    [[TAPChatManager sharedManager] saveAllUnsentMessage];
//
//    TapUIChatViewController *chatViewController = [[TapUIChatViewController alloc] initWithNibName:@"TapUIChatViewController" bundle:[TAPUtil currentBundle]];
//    chatViewController.currentRoom = room;
//    chatViewController.delegate = [[TapUI sharedInstance] roomListViewController];
//    [chatViewController setChatViewControllerType:TapUIChatViewControllerTypePeek];
//    //END DV Note
//
//    return chatViewController;
//}

//- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
//    TapUIChatViewController *chatViewController = (TapUIChatViewController *)viewControllerToCommit;
//    [chatViewController setChatViewControllerType:TapUIChatViewControllerTypeDefault];
//    [self.navigationController showViewController:chatViewController sender:nil];
//}

#pragma mark TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    TAPRoomListModel *selectedRoomList = [self.roomListArray objectAtIndex:indexPath.row];
    TAPMessageModel *selectedMessage = selectedRoomList.lastMessage;
    TAPRoomModel *selectedRoom = selectedMessage.room;
    
    [[TapUI sharedInstance] createRoomWithRoom:selectedRoom success:^(TapUIChatViewController * _Nonnull chatViewController) {
        chatViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:chatViewController animated:YES];
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.searchBarView.searchTextField.isFirstResponder) {
        [self.searchBarView.searchTextField resignFirstResponder];
    }
}


- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UIContextualAction *archivedAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [self.view endEditing:YES];
        completionHandler(YES);
        
        TAPRoomListModel *roomList = [self.roomListArray objectAtIndex:indexPath.row];
        TAPMessageModel *selectedMessage = roomList.lastMessage;
        TAPRoomModel *selectedRoom = selectedMessage.room;
        
        if(roomList.numberOfUnreadMessages > 0 || roomList.isMarkedAsUnread){
            roomList.numberOfUnreadMessages = 0;
            roomList.isMarkedAsUnread = NO;
            [self.unreadRoomIDs removeObject:selectedRoom.roomID];
            self.roomListArray[indexPath.row] = roomList;
            //[self.roomListView.roomListTableView reloadData];
            NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
            NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];
            [self updateCellDataAtIndexPath:cellIndexPath updateUnreadBubble:YES];
            
            [[TAPCoreMessageManager sharedManager] markAllMessagesInRoomAsReadWithRoomID:selectedRoom.roomID];
          //  [[TAPCoreMessageManager sharedManager] markMessageAsRead:selectedMessage];
            
            NSArray<TAPMessageModel *> *selectedMessageArray = @[selectedMessage];
            
            [[TAPCoreMessageManager sharedManager] markMessagesAsRead:selectedMessageArray success:^(NSArray<NSString *> *updatedMessageIDs){
                //[self callApiGetMarkedUnreadIDs];
             } failure:^(NSError *error) {
                 
             }];
        }
        else{
            [self.unreadRoomIDs addObject:selectedRoom.roomID];
            roomList.isMarkedAsUnread = YES;
            [[TAPCoreRoomListManager sharedManager] markChatRoomAsUnreadWithRoomID:selectedRoom.roomID success:^{
                // TODO: SAVE UNREAD IDS TO PREFERENCE
            }
            failure:^(NSError * _Nonnull error) {
                
            }];
            
           // [self.roomListView.roomListTableView reloadData];
            self.roomListArray[indexPath.row] = roomList;
            NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
            NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];
            [self updateCellDataAtIndexPath:cellIndexPath updateUnreadBubble:YES];
            
        }
        TAPRoomListModel *tt = [self.roomListArray objectAtIndex:indexPath.row];
        NSLog(@"===== isMarked:%ld", tt.isMarkedAsUnread);
        [TAPDataManager setUnreadRoomIDs:self.unreadRoomIDs];
        [self getAndUpdateNumberOfUnreadToDelegate];
    }];
    
    if(![[TapUI sharedInstance] getMarkAsUnreadRoomListSwipeMenuEnabled] && ![[TapUI sharedInstance] getMarkAsReadRoomListSwipeMenuEnabled]){
        
        return nil;
        
    }
    
    TAPRoomListModel *roomList = [self.roomListArray objectAtIndex:indexPath.row];
    if(roomList.numberOfUnreadMessages > 0 || roomList.isMarkedAsUnread){
        if(![[TapUI sharedInstance] getMarkAsReadRoomListSwipeMenuEnabled]){
            return nil;
            
        }
        self.readUnreadStateString = NSLocalizedStringFromTableInBundle(@"Read", nil, [TAPUtil currentBundle], @"");
        self.readUnreadStateImage = [UIImage imageNamed:@"TAPIconMarkRead" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil];
    }
    else{
        if(![[TapUI sharedInstance] getMarkAsUnreadRoomListSwipeMenuEnabled]){
            return nil;
            
        }
        self.readUnreadStateString = NSLocalizedStringFromTableInBundle(@"Unread", nil, [TAPUtil currentBundle], @"");
        self.readUnreadStateImage = [UIImage imageNamed:@"TAPIconMarkUnread" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil];
    }
    
    UIImage *imageRendered = [self createImageFromView:[self addedUIViewSwipeAction]];
    archivedAction.image = imageRendered;
    archivedAction.backgroundColor = [[TAPStyleManager sharedManager] getComponentColorForType:TAPComponentColorRoomListSwipeButtonBackground];
    
    NSArray *rowActionArray = @[archivedAction];
    
    return [UISwipeActionsConfiguration configurationWithActions:rowActionArray];
}

//- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath

#pragma mark TAPChatManager
- (void)chatManagerDidReceiveNewMessageOnOtherRoom:(TAPMessageModel *)message {
    [self processMessageFromSocket:message isNewMessage:YES];
}

- (void)chatManagerDidReceiveUpdateMessageOnOtherRoom:(TAPMessageModel *)message {
    [self processMessageFromSocket:message isNewMessage:NO];
}

- (void)chatManagerDidReceiveNewMessageInActiveRoom:(TAPMessageModel *)message {
    [self processMessageFromSocket:message isNewMessage:YES];
}

- (void)chatManagerDidReceiveUpdateMessageInActiveRoom:(TAPMessageModel *)message {
    [self processMessageFromSocket:message isNewMessage:NO];
}

- (void)chatManagerDidSendNewMessage:(TAPMessageModel *)message {
    [self processMessageFromSocket:message isNewMessage:YES];
}

- (void)chatManagerDidReceiveStartTyping:(TAPTypingModel *)typing {
    TAPRoomListModel *roomList = [self.roomListDictionary objectForKey:typing.roomID];
    
    NSInteger index = [self.roomListArray indexOfObject:roomList];
    TAPRoomListTableViewCell *cell = (TAPRoomListTableViewCell *)[self.roomListView.roomListTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [cell setAsTyping:YES];
}

- (void)chatManagerDidReceiveStopTyping:(TAPTypingModel *)typing {
    TAPRoomListModel *roomList = [self.roomListDictionary objectForKey:typing.roomID];

    NSInteger index = [self.roomListArray indexOfObject:roomList];
    TAPRoomListTableViewCell *cell = (TAPRoomListTableViewCell *)[self.roomListView.roomListTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [cell setAsTyping:NO];
}

#pragma mark UITextField
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.navigationItem.leftBarButtonItem = nil;
    [UIView animateWithDuration:0.2f animations:^{
        self.leftBarView.alpha = 0.0f;
    }];
    
    [UIView animateWithDuration:0.2f animations:^{
        self.searchBarView.frame = CGRectMake(
            -55.0f,
            CGRectGetMinY(self.searchBarView.frame),
            CGRectGetWidth([UIScreen mainScreen].bounds) - 73.0f - 16.0f,
            CGRectGetHeight(self.searchBarView.frame)
        );

        UIFont *searchBarCancelFont = [[TAPStyleManager sharedManager] getComponentFontForType:TAPComponentFontSearchBarTextCancelButton];
        UIColor *searchBarCancelColor = [[TAPStyleManager sharedManager] getTextColorForType:TAPTextColorSearchBarTextCancelButton];
        self.rightBarButton.frame = CGRectMake(0.0f, 0.0f, 51.0f, 40.0f);
        [self.rightBarButton setTitle:NSLocalizedStringFromTableInBundle(@"Cancel", nil, [TAPUtil currentBundle], @"") forState:UIControlStateNormal];
        [self.rightBarButton setTitleColor:searchBarCancelColor forState:UIControlStateNormal];
        self.rightBarButton.contentEdgeInsets  = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
        self.rightBarButton.titleLabel.font = searchBarCancelFont;
        [self.rightBarButton setImage:nil forState:UIControlStateNormal];
        [self.rightBarButton addTarget:self action:@selector(cancelButtonDidTapped) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBarButton];
        [self.navigationItem setRightBarButtonItem:rightBarButtonItem];
        
    } completion:^(BOOL finished) {
        TAPSearchViewController *searchViewController = [[TAPSearchViewController alloc] init];
        searchViewController.delegate = self;
        UINavigationController *searchNavigationController = [[UINavigationController alloc] initWithRootViewController:searchViewController];
        searchNavigationController.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:searchNavigationController animated:NO completion:^{
            [self setUpNavigationBar];
        }];
    }];
    
    return NO;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    
    return YES;
}

#pragma mark TAPConnectionStatusViewController
- (void)connectionStatusViewControllerDelegateHeightChange:(CGFloat)height {
#ifdef DEBUG
//    DV Note - v1.0.18
//    28 Nov 2019 - Temporary comment to hide connecting, waiting for network, connected state for further changing UI flow
    NSLog(@"===============connectionStatusViewControllerDelegateHeightChange");
        [UIView animateWithDuration:0.2f animations:^{
            //change frame
            self.roomListView.roomListTableView.frame = CGRectMake(CGRectGetMinX(self.roomListView.roomListTableView.frame), height, CGRectGetWidth(self.roomListView.roomListTableView.frame), CGRectGetHeight(self.roomListView.roomListTableView.frame));
        }];
//    END DV Note
#endif

}

#pragma mark TAPAddNewChatViewController
- (void)addNewChatViewControllerShouldOpenNewRoomWithUser:(TAPUserModel *)user {
    [[TapUI sharedInstance] createRoomWithOtherUser:user success:^(TapUIChatViewController * _Nonnull chatViewController) {
        chatViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:chatViewController animated:YES];
    }];
}

- (void)chatViewControllerDidLeaveOrDeleteGroupWithRoom:(TAPRoomModel *)room {
    //Delete room & refresh the UI
    TAPRoomListModel *deletedRoomList = [self.roomListDictionary objectForKey:room.roomID];
    if (deletedRoomList) {
        NSInteger deletedIndex = [self.roomListArray indexOfObject:deletedRoomList];
        [self.roomListArray removeObjectAtIndex:deletedIndex];
        [self.roomListDictionary removeObjectForKey:room.roomID];
        
        NSIndexPath *deletedIndexPath = [NSIndexPath indexPathForRow:deletedIndex inSection:0];
        [self.roomListView.roomListTableView deleteRowsAtIndexPaths:@[deletedIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

#pragma mark TapUIChatViewController
- (void)chatViewControllerShouldUpdateUnreadBubbleForRoomID:(NSString *)roomID {
    NSInteger readCount = [[TAPMessageStatusManager sharedManager] getReadCountAndClearDictionaryForRoomID:roomID];
    NSInteger readMentionCount = [[TAPMessageStatusManager sharedManager] getReadMentionCountAndClearDictionaryForRoomID:roomID];
    
    TAPRoomListModel *roomList = [self.roomListDictionary objectForKey:roomID];
    roomList.numberOfUnreadMessages = roomList.numberOfUnreadMessages - readCount;
    roomList.numberOfUnreadMentions = roomList.numberOfUnreadMentions - readMentionCount;
    
    if(roomList.numberOfUnreadMessages < 0) {
        roomList.numberOfUnreadMessages = 0;
    }
    
    if(roomList.numberOfUnreadMentions < 0) {
        roomList.numberOfUnreadMentions = 0;
    }
    
    TAPMessageModel *selectedMessage = roomList.lastMessage;
    TAPRoomModel *selectedRoom = selectedMessage.room;
    roomList.isMarkedAsUnread = NO;
    [self.unreadRoomIDs removeObject:selectedRoom.roomID];
    [self callApiGetMarkedUnreadIDs];
    
    NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
    NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];
    [self updateCellDataAtIndexPath:cellIndexPath updateUnreadBubble:YES];
}

- (void)chatViewControllerShouldClearUnreadBubbleForRoomID:(NSString *)roomID {
    //Force mark unread bubble and unread mention to 0
    TAPRoomListModel *roomList = [self.roomListDictionary objectForKey:roomID];
    TAPMessageModel *selectedMessage = roomList.lastMessage;
    TAPRoomModel *selectedRoom = selectedMessage.room;
    roomList.numberOfUnreadMessages = 0;
    roomList.numberOfUnreadMentions = 0;
    roomList.isMarkedAsUnread = NO;
    [self.unreadRoomIDs removeObject:selectedRoom.roomID];
    [self callApiGetMarkedUnreadIDs];
        
    NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
    NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];
    [self updateCellDataAtIndexPath:cellIndexPath updateUnreadBubble:YES];
}

#pragma mark TAPSearchViewController
- (void)searchViewControllerDidTappedSearchCancelButton {
    [UIView animateWithDuration:0.2f animations:^{
        self.leftBarView.alpha = 1.0f;
    }];
}

#pragma mark TAPMyAccountViewController
- (void)myAccountViewControllerDidTappedLogoutButton {
    [self.roomListArray removeAllObjects];
    [self.roomListDictionary removeAllObjects];
    [self.roomListView.roomListTableView reloadData];
}

- (void)myAccountViewControllerDoneChangingImageProfile {
    NSString *profileImageURL = [TAPChatManager sharedManager].activeUser.imageURL.thumbnail;
    if (profileImageURL == nil || [profileImageURL isEqualToString:@""]) {
        if ([TAPChatManager sharedManager].activeUser.fullname == nil || [[TAPChatManager sharedManager].activeUser.fullname isEqualToString:@""]) {
            self.leftBarInitialNameView.alpha = 0.0f;
            self.profileImageView.alpha = 1.0f;
            self.profileImageView.image = [UIImage imageNamed:@"TAPIconDefaultAvatar" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil];
        }
        else {
            self.leftBarInitialNameView.alpha = 1.0f;
            self.leftBarInitialNameView.userInteractionEnabled = NO;
            self.profileImageView.alpha = 0.0f;
            self.leftBarInitialNameView.backgroundColor = [[TAPStyleManager sharedManager] getRandomDefaultAvatarBackgroundColorWithName:[TAPChatManager sharedManager].activeUser.fullname];
            self.leftBarInitialNameLabel.text = [[TAPStyleManager sharedManager] getInitialsWithName:[TAPChatManager sharedManager].activeUser.fullname isGroup:NO];
        }
    }
    else {
        self.leftBarInitialNameView.alpha = 0.0f;
        self.profileImageView.alpha = 1.0f;
        [self.profileImageView setImageWithURLString:profileImageURL];
    }
}

#pragma mark UIAdaptivePresentationController
- (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController {
    NSString *profileImageURL = [TAPChatManager sharedManager].activeUser.imageURL.thumbnail;
    if (profileImageURL == nil || [profileImageURL isEqualToString:@""]) {
        if ([TAPChatManager sharedManager].activeUser.fullname == nil || [[TAPChatManager sharedManager].activeUser.fullname isEqualToString:@""]) {
            self.leftBarInitialNameView.alpha = 0.0f;
            self.profileImageView.alpha = 1.0f;
            self.profileImageView.image = [UIImage imageNamed:@"TAPIconDefaultAvatar" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil];
        }
        else {
            self.leftBarInitialNameView.alpha = 1.0f;
            self.profileImageView.alpha = 0.0f;
            self.leftBarInitialNameView.backgroundColor = [[TAPStyleManager sharedManager] getRandomDefaultAvatarBackgroundColorWithName:[TAPChatManager sharedManager].activeUser.fullname];
            self.leftBarInitialNameLabel.text = [[TAPStyleManager sharedManager] getInitialsWithName:[TAPChatManager sharedManager].activeUser.fullname isGroup:NO];
        }
    }
    else {
        self.leftBarInitialNameView.alpha = 0.0f;
        self.profileImageView.alpha = 1.0f;
        [self.profileImageView setImageWithURLString:profileImageURL];
    }
}

#pragma mark - Custom Method

- (void)setUpNavigationBar {
    BOOL showCloseButton = [[TapUI sharedInstance] getCloseRoomListButtonVisibleState];
    BOOL showMyAccountButton = [[TapUI sharedInstance] getMyAccountButtonInRoomListViewVisibleState];
    BOOL showSearchBar = [[TapUI sharedInstance] getSearchBarInRoomListVisibleState];
    BOOL showNewChatButton = [[TapUI sharedInstance] getNewChatButtonInRoomListVisibleState];
    
    if (showCloseButton || showMyAccountButton) {
        if (showCloseButton) {
            UIImage *buttonImage = [UIImage imageNamed:@"TAPIconClose" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil];
            buttonImage = [buttonImage setImageTintColor:[[TAPStyleManager sharedManager] getComponentColorForType:TAPComponentColorIconNavigationBarCloseButton]];
            self.closeButton.frame = CGRectMake(-20.0f, 0.0f, 40.0f, 40.0f);
            self.closeButton.contentEdgeInsets = UIEdgeInsetsMake(0.0f, 18.0f, 0.0f, 0.0f);
            [self.closeButton setImage:buttonImage forState:UIControlStateNormal];
            [self.closeButton addTarget:self action:@selector(closeButtonDidTapped) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (showMyAccountButton) {
            CGFloat myAccountButtonX;
            if (showCloseButton) {
                myAccountButtonX = CGRectGetMaxX(self.closeButton.frame) + 8.0f;
            }
            else {
                myAccountButtonX = 0.0f;
            }
            
            self.myAccountButton.frame = CGRectMake(myAccountButtonX, 0.0f, 40.0f, 40.0f);

            self.leftBarInitialNameView.frame = CGRectMake(5.0f, 5.0f, 30.0f, 30.0f);
            self.leftBarInitialNameView.alpha = 0.0f;
            self.leftBarInitialNameView.layer.cornerRadius = CGRectGetHeight(self.leftBarInitialNameView.frame) / 2.0f;
            self.leftBarInitialNameView.clipsToBounds = YES;
            [self.myAccountButton addSubview:self.leftBarInitialNameView];
            
            UIFont *initialNameLabelFont = [[TAPStyleManager sharedManager] getComponentFontForType:TAPComponentFontRoomAvatarSmallLabel];
            UIColor *initialNameLabelColor = [[TAPStyleManager sharedManager] getTextColorForType:TAPTextColorRoomAvatarSmallLabel];
            self.leftBarInitialNameLabel.frame = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.leftBarInitialNameView.frame), CGRectGetHeight(self.leftBarInitialNameView.frame));
            self.leftBarInitialNameLabel.font = initialNameLabelFont;
            self.leftBarInitialNameLabel.textColor = initialNameLabelColor;
            self.leftBarInitialNameLabel.textAlignment = NSTextAlignmentCenter;
            [self.leftBarInitialNameView addSubview:self.leftBarInitialNameLabel];
            
            self.leftBarInitialNameButton.frame = self.leftBarInitialNameView.frame;
            self.leftBarInitialNameButton.alpha = 0.0f;
            self.leftBarInitialNameButton.userInteractionEnabled = NO;
            self.leftBarInitialNameButton.layer.cornerRadius = CGRectGetHeight(self.leftBarInitialNameButton.frame) / 2.0f;
            [self.leftBarInitialNameButton addTarget:self action:@selector(leftBarButtonDidTapped) forControlEvents:UIControlEventTouchUpInside];
            [self.leftBarInitialNameView addSubview:self.leftBarInitialNameButton];
            
            self.profileImageView.frame = CGRectMake(5.0f, 5.0f, 30.0f, 30.0f);
            self.profileImageView.layer.cornerRadius = CGRectGetHeight(self.profileImageView.bounds) / 2.0f;
            self.profileImageView.clipsToBounds = YES;
            self.profileImageView.contentMode = UIViewContentModeScaleAspectFill;
            [self.myAccountButton addSubview:self.profileImageView];
        
            [self.myAccountButton addTarget:self action:@selector(leftBarButtonDidTapped) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (showCloseButton && showMyAccountButton) {
            self.leftBarView.frame = CGRectMake(
                0.0f,
                0.0f,
                CGRectGetMaxX(self.myAccountButton.frame),
                40.0f
            );
            [self.leftBarView addSubview:self.closeButton];
            [self.leftBarView addSubview:self.myAccountButton];
        }
        else if (showMyAccountButton) {
            self.leftBarView.frame = CGRectMake(
                0.0f,
                0.0f,
                CGRectGetMaxX(self.myAccountButton.frame),
                40.0f
            );
            [self.leftBarView addSubview:self.myAccountButton];
        }
        else if (showCloseButton) {
            self.leftBarView.frame = CGRectMake(
                0.0f,
                0.0f,
                CGRectGetMaxX(self.closeButton.frame),
                40.0f
            );
            [self.leftBarView addSubview:self.closeButton];
        }
        UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftBarView];
        [self.navigationItem setLeftBarButtonItem:leftBarButtonItem];
    }
    else {
        [self.navigationItem setLeftBarButtonItem:nil];
    }
        
    if (showNewChatButton) {
        //RightBarButton
        UIImage *rightBarImage = [UIImage imageNamed:@"TAPIconAddEditItem" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil];
        rightBarImage = [rightBarImage setImageTintColor:[[TAPStyleManager sharedManager] getComponentColorForType:TAPComponentColorIconStartNewChatButton]];

        self.rightBarButton.frame = CGRectMake(0.0f, 0.0f, 40.0f, 40.0f);
        self.rightBarButton.contentEdgeInsets = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, -9.0f);
        [self.rightBarButton setImage:rightBarImage forState:UIControlStateNormal];
        [self.rightBarButton setTitle:nil forState:UIControlStateNormal];
        [self.rightBarButton addTarget:self action:@selector(rightBarButtonDidTapped) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBarButton];
        
        [self.navigationItem setRightBarButtonItem:rightBarButtonItem];
    }
    else {
        self.rightBarButton.frame = CGRectMake(0.0f, 0.0f, 0.0f, 0.0f);
        [self.navigationItem setRightBarButtonItem:nil];
    }
    
    if (showSearchBar) {
        //TitleView
        self.searchBarView.frame = CGRectMake(
            0.0f,
            0.0f,
            CGRectGetWidth([UIScreen mainScreen].bounds) - CGRectGetWidth(self.leftBarView.frame) - CGRectGetWidth(self.rightBarButton.frame) - 36.0f,
            30.0f
        );
        self.searchBarView.searchTextField.delegate = self;
        
        [self.navigationItem setTitleView:self.searchBarView];
    }
    else {
        self.title = NSLocalizedStringFromTableInBundle(@"Chats", nil, [TAPUtil currentBundle], @"");
    }
}

- (void)leftBarButtonDidTapped {
    id <TapUIRoomListDelegate> roomListDelegate = [TapUI sharedInstance].roomListDelegate;
    if ([roomListDelegate respondsToSelector:@selector(tapTalkAccountButtonTapped:currentShownNavigationController:)]) {
        [roomListDelegate tapTalkAccountButtonTapped:self currentShownNavigationController:self.navigationController];
    }
    else {
        TAPMyAccountViewController *myAccountViewController = [[TAPMyAccountViewController alloc] init];
        myAccountViewController.delegate = self;
        //myAccountViewController.presentationController.delegate = self;
        //UINavigationController *myAccountNavigationController = [[UINavigationController alloc] initWithRootViewController:myAccountViewController];
       // [self presentViewController:myAccountNavigationController animated:YES completion:nil];
        [self.navigationController pushViewController:myAccountViewController animated:YES];
    }
}

- (void)rightBarButtonDidTapped {
    id <TapUIRoomListDelegate> roomListDelegate = [TapUI sharedInstance].roomListDelegate;
    if ([roomListDelegate respondsToSelector:@selector(tapTalkNewChatButtonTapped:currentShownNavigationController:)]) {
        [roomListDelegate tapTalkNewChatButtonTapped:self currentShownNavigationController:self.navigationController];
    }
    else {
        [self openNewChatViewController];
    }
}

- (void)cancelButtonDidTapped {
//    [self.searchBarView.searchTextField resignFirstResponder];
//    self.searchBarView.searchTextField.text = @"";
}

- (void)mappingMessageArrayToRoomListArrayAndDictionary:(NSArray *)messageArray {
    if (_roomListArray != nil) {
        [self.roomListArray removeAllObjects];
        _roomListArray = nil;
    }
    
    if (_roomListDictionary != nil) {
        [self.roomListDictionary removeAllObjects];
        _roomListDictionary = nil;
    }
    
    _roomListDictionary = [[NSMutableDictionary alloc] init];
    _roomListArray = [[NSMutableArray alloc] init];
    
    NSArray *unreadRoomArray = [self.unreadRoomIDs copy];
    
    for (TAPMessageModel *message in messageArray) {
        TAPRoomModel *room = message.room;
        NSString *roomID = room.roomID;
        roomID = [TAPUtil nullToEmptyString:roomID];
        
        TAPRoomListModel *roomList = [TAPRoomListModel new];
        roomList.lastMessage = message;
        if([unreadRoomArray containsObject:room.roomID]){
            roomList.isMarkedAsUnread = YES;
        }
        
        [self insertRoomListToArrayAndDictionary:roomList atIndex:[self.roomListArray count]];
    }
    
    [self getAndUpdateNumberOfUnreadToDelegate];
    
}

- (void)insertRoomListToArrayAndDictionary:(TAPRoomListModel *)roomList atIndex:(NSInteger)index {
    [self.roomListArray insertObject:roomList atIndex:index];
    [self.roomListDictionary setObject:roomList forKey:roomList.lastMessage.room.roomID];
}

- (void)viewLoadedSequence {
    //Check if should show first loading view
    if ([TAPChatManager sharedManager].activeUser == nil) {
        [[TAPChatManager sharedManager] disconnect];
        
        if([TapTalk sharedInstance].isAuthenticated) {
    
            BOOL isDoneFirstSetup = [[NSUserDefaults standardUserDefaults] secureBoolForKey:TAP_PREFS_IS_DONE_FIRST_SETUP valid:nil];
            if (!isDoneFirstSetup) {
                [self.setupRoomListView showSetupViewWithType:TAPSetupRoomListViewTypeSettingUp];
                [self.setupRoomListView showFirstLoadingView:YES withType:TAPSetupRoomListViewTypeSettingUp];
            }
            
            id<TapTalkDelegate> tapTalkDelegate = [TapTalk sharedInstance].delegate;
            if ([tapTalkDelegate respondsToSelector:@selector(tapTalkRefreshTokenExpired)]) {
                [tapTalkDelegate tapTalkRefreshTokenExpired];
            }
        }
        else {
            //User not authenticated
            [self.setupRoomListView showSetupViewWithType:TAPSetupRoomListViewTypeFailed];
            [self.setupRoomListView showFirstLoadingView:YES withType:TAPSetupRoomListViewTypeFailed];
            
            NSLog(@"****************************************************\n\n\n");
            NSLog(@"TapTalk.io - Could not find active user data. Please make sure the client app is authenticated.");
            NSLog(@"\n\n\n****************************************************");
        }
        
        return; //User not logged in
    }
    
    if (self.isShouldNotLoadFromAPI) {
        //Load from database only
        [self reloadLocalDataAndUpdateUILogicAnimated:NO];
    }
    else {
        //Load from API and database
        _isShouldNotLoadFromAPI = YES;
        [self runFullRefreshSequence];
    }
}

- (void)runFullRefreshSequence {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        //Save pending messages, new messages, waiting response messages, and waiting upload file messages to database
        [[TAPChatManager sharedManager] saveAllUnsentMessageInMainThread];
        
        [TAPDataManager getRoomListSuccess:^(NSArray *resultArray) {
            dispatch_async(dispatch_get_main_queue(), ^{
                BOOL isShouldAnimate = YES;
                
                if (self.roomListArray == nil || [self.roomListArray count] <= 0) {
                    isShouldAnimate = NO;
                }
                
                [self refreshViewAndQueryUnreadLogicWithMessageArray:resultArray animateReloadData:isShouldAnimate];
                
                
                [self fetchDataFromAPI];
            });
        } failure:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideSetupViewWithDelay:0.0f];
            });
        }];
    });
    
    
}

- (void)fetchDataFromAPI {
    TAPUserModel *activeUser = [TAPChatManager sharedManager].activeUser;
    NSString *userID = activeUser.userID;
    userID = [TAPUtil nullToEmptyString:userID];
    
    BOOL isDoneFirstSetup = [[NSUserDefaults standardUserDefaults] secureBoolForKey:TAP_PREFS_IS_DONE_FIRST_SETUP valid:nil];
    if (!isDoneFirstSetup) {
        //First setup, run get room list and unread message
        [self showLoadingSetupView];
        [TAPDataManager callAPIGetMessageRoomListAndUnreadWithUserID:userID success:^(NSArray *messageArray) {
            //Call API Get Unread Room List
            [TAPDataManager callAPIGetMarkedAsUnreadChatRoomList:^(NSArray <NSString *> *roomIDs){
                //handle pref
                [TAPDataManager setUnreadRoomIDs:roomIDs];
                [self handleRommlistAndUnreadSuccess:messageArray];
            } failure:^(NSError *error) {
                [self handleRommlistAndUnreadSuccess:messageArray];
            }];
        } failure:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.isShouldNotLoadFromAPI = NO;
                [self.setupRoomListView showSetupViewWithType:TAPSetupRoomListViewTypeFailed];
                [self.setupRoomListView showFirstLoadingView:YES withType:TAPSetupRoomListViewTypeFailed];
            });
        }];
        
        return;
    }
    
    //Not first setup, get new and updated message
    [TAPDataManager callAPIGetNewAndUpdatedMessageSuccess:^(NSArray *messageArray) {
       
        [TAPDataManager callAPIGetMarkedAsUnreadChatRoomList:^(NSArray<NSString *> *roomIDs){
            //handle pref
            [TAPDataManager setUnreadRoomIDs:roomIDs];
            [self handleNewAndUpdatedSuccess:messageArray];
        } failure:^(NSError *error) {
            //handle pref
            [self handleNewAndUpdatedSuccess:messageArray];
        }];
        
    } failure:^(NSError *error) {
        self.isShouldNotLoadFromAPI = NO;
    }];
}

- (void)handleRommlistAndUnreadSuccess:(NSArray *)messageArray{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSUserDefaults standardUserDefaults] setSecureBool:YES forKey:TAP_PREFS_IS_DONE_FIRST_SETUP];
        [[NSUserDefaults standardUserDefaults] synchronize];
    });
    
    [self insertReloadMessageAndUpdateUILogicWithMessageArray:messageArray];
}

- (void)handleNewAndUpdatedSuccess:(NSArray *)messageArray{
    [self insertReloadMessageAndUpdateUILogicWithMessageArray:messageArray];
    
    //Update self profile
    [self checkAndUpdateActiveUserProfile];
    
    //Update leftover message status to delivered
    if ([messageArray count] != 0) {
        [[TAPMessageStatusManager sharedManager] filterAndUpdateBulkMessageStatusToDeliveredWithArray:messageArray];
    }
    
    //Delete physical files when isDeleted = 1 (message is deleted)
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        for (TAPMessageModel *message in messageArray) {
            if (message.isDeleted) {
                [TAPDataManager deletePhysicalFilesInBackgroundWithMessage:message success:^{
                    
                } failure:^(NSError *error) {
                    
                }];
            }
        }
    });
}

- (void)insertReloadMessageAndUpdateUILogicWithMessageArray:(NSArray *)messageArray {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        //Save messages to database
        [TAPDataManager updateOrInsertDatabaseMessageInMainThreadWithData:messageArray success:^{
            //Get room list data from database and refresh UI
            [self reloadLocalDataAndUpdateUILogicAnimated:YES];
        } failure:^(NSError *error) {
            
        }];
    });
}

- (void)reloadLocalDataAndUpdateUILogicAnimated:(BOOL)animated {
    [TAPDataManager getRoomListSuccess:^(NSArray *resultArray) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.setupRoomListView showSetupViewWithType:TAPSetupRoomListViewTypeSuccess];
            [self hideSetupViewWithDelay:0.5f];
            [[NSUserDefaults standardUserDefaults] setSecureBool:YES forKey:TAP_PREFS_IS_DONE_FIRST_SETUP];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [self refreshViewAndQueryUnreadLogicWithMessageArray:resultArray animateReloadData:animated];
        });
    } failure:^(NSError *error) {
        
    }];
}

- (void)refreshViewAndQueryUnreadLogicWithMessageArray:(NSArray *)messageArray animateReloadData:(BOOL)animateReloadData {
    BOOL isDoneFirstSetup = [[NSUserDefaults standardUserDefaults] secureBoolForKey:TAP_PREFS_IS_DONE_FIRST_SETUP valid:nil];
    
    if (!isDoneFirstSetup) {
        [self.roomListView showNoChatsView:NO];
    }
    else if ([self.roomListArray count] <= 0 && [messageArray count] <= 0) {
        //Show no chat view
        [self.roomListView showNoChatsView:YES];
    }
    else if ([self.roomListArray count] <= 0 && [messageArray count] > 0) {
        //Show data first before query unread message
        [self.roomListView showNoChatsView:NO];
        [self mappingMessageArrayToRoomListArrayAndDictionary:messageArray];
        
        [UIView performWithoutAnimation:^{ //Try to remove table view reload data flicker
            [self.roomListView.roomListTableView reloadData];
            [self.roomListView.roomListTableView layoutIfNeeded];
        }];
    }
    else {
        //Save old sequence to array and database
        NSMutableArray *oldRoomListArray = [NSMutableArray arrayWithArray:self.roomListArray];
        NSMutableDictionary *oldRoomListDictionary = [NSMutableDictionary dictionaryWithDictionary:self.roomListDictionary];
        
        [self.roomListView showNoChatsView:NO];
        [self mappingMessageArrayToRoomListArrayAndDictionary:messageArray];
        
        if (animateReloadData && self.isViewAppear) {
            //Update UI movement changes animation
            
            NSMutableArray *insertIndexArray = [NSMutableArray array];
            NSMutableArray *moveFromIndexArray = [NSMutableArray array];
            NSMutableArray *moveToIndexArray = [NSMutableArray array];
            
            for (NSInteger newIndex = 0; newIndex < [self.roomListArray count]; newIndex++) {
                TAPRoomListModel *newRoomList = [self.roomListArray objectAtIndex:newIndex];
                
                if (newRoomList == nil) {
                    continue;
                }
                
                TAPRoomListModel *oldRoomList = [oldRoomListDictionary objectForKey:newRoomList.lastMessage.room.roomID];
                
                if (oldRoomList == nil) {
                    //Room list not found in old data, so this is a new room
                    //Populate old data
                    [oldRoomListArray insertObject:newRoomList atIndex:newIndex];
                    [oldRoomListDictionary setObject:newRoomList forKey:newRoomList.lastMessage.room.roomID];
                    
                    [insertIndexArray addObject:[NSIndexPath indexPathForRow:newIndex inSection:0]];
                    //Insert to table view
//                    [self.roomListView.roomListTableView beginUpdates];
//                    [self.roomListView.roomListTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:newIndex inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
//                    [self.roomListView.roomListTableView endUpdates];
                    continue;
                }
                
                NSInteger oldIndex = [oldRoomListArray indexOfObject:oldRoomList];
                
                if (newIndex == oldIndex) {
                    //Index is same, no need to move cell, just update data
                    [self updateCellDataAtIndexPath:[NSIndexPath indexPathForRow:oldIndex inSection:0] updateUnreadBubble:NO];
                    continue;
                }
                
                //Move cell to new index
                //Populate old data
                [oldRoomListArray removeObjectAtIndex:oldIndex];
                [oldRoomListArray insertObject:oldRoomList atIndex:newIndex];
                
                [moveFromIndexArray addObject:[NSString stringWithFormat:@"%ld", oldIndex]];
                [moveToIndexArray addObject:[NSString stringWithFormat:@"%ld", newIndex]];
                
                //Update table view
//                [self updateCellDataAtIndexPath:[NSIndexPath indexPathForRow:oldIndex inSection:0] updateUnreadBubble:NO];
//                [self.roomListView.roomListTableView beginUpdates];
//                [self.roomListView.roomListTableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:oldIndex inSection:0] toIndexPath:[NSIndexPath indexPathForRow:newIndex inSection:0]];
//                [self.roomListView.roomListTableView endUpdates];
            }
            
            //Handle room insert
            if([insertIndexArray count] > 0) {
                [self.roomListView.roomListTableView performBatchUpdates:^{
                    //changing beginUpdates and endUpdates with this because of deprecation
                    [self.roomListView.roomListTableView insertRowsAtIndexPaths:insertIndexArray withRowAnimation:UITableViewRowAnimationAutomatic];
                } completion:^(BOOL finished) {
                    [self.roomListView.roomListTableView scrollsToTop];
                }];
            }
            
            //Handle room move
            if ([moveFromIndexArray count] > 0) {
                for (int count = 0; count < [moveFromIndexArray count]; count++) {
                    NSInteger oldIndex = [[moveFromIndexArray objectAtIndex:count] intValue];
                    NSInteger newIndex = [[moveToIndexArray objectAtIndex:count] intValue];
                    
                    [self updateCellDataAtIndexPath:[NSIndexPath indexPathForRow:oldIndex inSection:0] updateUnreadBubble:NO];
                    [self.roomListView.roomListTableView performBatchUpdates:^{
                        //changing beginUpdates and endUpdates with this because of deprecation
                        [self.roomListView.roomListTableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:oldIndex inSection:0] toIndexPath:[NSIndexPath indexPathForRow:newIndex inSection:0]];
                    } completion:^(BOOL finished) {
                    }];
                }
            }
            
            //Handle room deletion
            NSArray *loopedRoomListArray = [NSArray arrayWithArray:oldRoomListArray];
            for (NSInteger index = 0; index < [loopedRoomListArray count]; index++) {
                TAPRoomListModel *oldRoomList = [oldRoomListArray objectAtIndex:index];
                
                if (oldRoomList == nil) {
                    continue;
                }
                
                //Check if room list exist in new response
                TAPRoomListModel *newRoomList = [self.roomListDictionary objectForKey:oldRoomList.lastMessage.room.roomID];
                
                if (newRoomList == nil) {
                    //Data not exist, delete cell
                    NSInteger oldIndex = [oldRoomListArray indexOfObject:oldRoomList];
                    [oldRoomListArray removeObjectAtIndex:oldIndex];
                    [self.roomListView.roomListTableView performBatchUpdates:^{
                        //changing beginUpdates and endUpdates with this because of deprecation
                        [self.roomListView.roomListTableView deleteRowsAtIndexPaths:[NSIndexPath indexPathForRow:oldIndex inSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
                    } completion:^(BOOL finished) {
                    }];
                }
            }
        }
        else if (!self.isViewAppear) {
            //View not appear, just reload table view without animation
            [UIView performWithoutAnimation:^{ //Try to remove table view reload data flicker
                [self.roomListView.roomListTableView reloadData];
                [self.roomListView.roomListTableView layoutIfNeeded];
            }];
        }
    }
    
    //Query unread count and update UI
    [self queryNumberOfUnreadMessageInRoomListArrayInBackgroundAndUpdateUIAndReloadTableView:!animateReloadData];
}

- (void)queryNumberOfUnreadMessageInRoomListArrayInBackgroundAndUpdateUIAndReloadTableView:(BOOL)reloadTableView {
    NSArray *roomListLocalArray = [NSArray arrayWithArray:self.roomListArray];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        if ([roomListLocalArray count] == 0) {
            return;
        }
        
        _firstUnreadProcessCount = 0;
        _firstUnreadTotalCount = [roomListLocalArray count];
        NSMutableDictionary *unreadMentionDataDictionary = [NSMutableDictionary dictionary];
        
        for (TAPRoomListModel *roomList in roomListLocalArray) {
            TAPMessageModel *messageData = roomList.lastMessage;
            TAPRoomModel *roomData = messageData.room;
            NSString *roomIDString = roomData.roomID;
            roomIDString = [TAPUtil nullToEmptyString:roomIDString];
            
            NSString *usernameString = [TAPDataManager getActiveUser].username;
            usernameString = [TAPUtil nullToEmptyString:usernameString];
            NSString *activeUserID = [TAPDataManager getActiveUser].userID;
            activeUserID = [TAPUtil nullToEmptyString:activeUserID];
            
            [TAPDataManager getDatabaseUnreadMentionsInRoomWithUsername:usernameString roomID:roomIDString activeUserID:activeUserID success:^(NSArray *unreadMentionMessages) {
                NSInteger totalUnreadMention = [unreadMentionMessages count];
                [unreadMentionDataDictionary setObject:[NSNumber numberWithInteger:totalUnreadMention] forKey:roomIDString];
                
                [TAPDataManager getDatabaseUnreadMessagesInRoomWithRoomID:roomIDString activeUserID:[TAPChatManager sharedManager].activeUser.userID success:^(NSArray *unreadMessages) {
                    //Set number of unread messages to array and dictionary
                    NSInteger numberOfUnreadMessages = [unreadMessages count];
                    NSInteger numberOfUnreadMentions = [[unreadMentionDataDictionary objectForKey:roomIDString] integerValue];
                    TAPRoomListModel *roomList = [self.roomListDictionary objectForKey:roomIDString];
                    roomList.numberOfUnreadMessages = numberOfUnreadMessages;
                    roomList.numberOfUnreadMentions = numberOfUnreadMentions;
                    
                    if(roomList.numberOfUnreadMessages < 0) {
                        roomList.numberOfUnreadMessages = 0;
                    }
                    
                    if(roomList.numberOfUnreadMentions < 0) {
                        roomList.numberOfUnreadMentions = 0;
                    }
                    
                    _firstUnreadProcessCount++;
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if(self.firstUnreadProcessCount >= self.firstUnreadTotalCount) {
                            [self getAndUpdateNumberOfUnreadToDelegate];
                        }
                        
                        NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
                        NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];
                        [self updateCellDataAtIndexPath:cellIndexPath updateUnreadBubble:YES];
                    });
                } failure:^(NSError *error) {

                }];
            } failure:^(NSError *error) {
                
            }];
        }
        
        if (reloadTableView) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView performWithoutAnimation:^{ //Try to remove table view reload data flicker
                    [self.roomListView.roomListTableView reloadData];
                    [self.roomListView.roomListTableView layoutIfNeeded];
                }];
            });
        }
    });
}

- (void)processMessageFromSocket:(TAPMessageModel *)message isNewMessage:(BOOL)isNewMessage {
    NSString *messageRoomID = message.room.roomID;
    
    //Check need to update user data or not
    if (message.type == TAPChatMessageTypeSystemMessage && ([message.action isEqualToString:@"user/update"] || [message.action isEqualToString:@"room/update"])) {
        [self checkUpdatedUserProfileWithMessage:message];
    }
    
    TAPRoomListModel *roomList = [self.roomListDictionary objectForKey:messageRoomID];
    
    if (roomList != nil) {
        //Room is on the list
        TAPMessageModel *roomLastMessage = roomList.lastMessage;
        
        if (message.isHidden) {
            //Don't process last message that is hidden
            return;
        }
        
        if([roomLastMessage.created integerValue] > [message.created integerValue]) {
            //Don't process last message, current last message is newer that the incoming one
            return;
        }
        
        if ([roomLastMessage.localID isEqualToString:message.localID]) {
            //Last message is same, just updated, update the data only
            roomLastMessage.updated = message.updated;
            roomLastMessage.isDeleted = message.isDeleted;
            roomLastMessage.isSending = message.isSending;
            roomLastMessage.isFailedSend = message.isFailedSend;
            roomLastMessage.isRead = message.isRead;
            roomLastMessage.isDelivered = message.isDelivered;
            roomLastMessage.isHidden = message.isHidden;
            
            NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];
            [self updateCellDataAtIndexPath:indexPath updateUnreadBubble:NO];
        }
        else {
            //Last message is different, move cell to top and update last message
            roomList.lastMessage = message;

            if (![message.user.userID isEqualToString:[TAPChatManager sharedManager].activeUser.userID] && isNewMessage) {
                //Message from other recipient, increment number of unread message
                roomList.numberOfUnreadMessages++;
                
                BOOL hasMention = [TAPUtil isActiveUserMentionedWithMessage:message activeUser:[TAPDataManager getActiveUser]];
                if (hasMention) {
                    roomList.numberOfUnreadMentions++;
                }
            }

            NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
            NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];

            [self updateCellDataAtIndexPath:currentIndexPath updateUnreadBubble:YES];

            if (currentIndexPath != 0 && isNewMessage) {
                //Move cell to top
                [self.roomListArray removeObject:roomList];
                [self.roomListArray insertObject:roomList atIndex:0];
                [self.roomListView.roomListTableView performBatchUpdates:^{
                    //changing beginUpdates and endUpdates with this because of deprecation
                    [self.roomListView.roomListTableView moveRowAtIndexPath:currentIndexPath toIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                } completion:^(BOOL finished) {
                }];
            }
        }
    }
    else {
        //Room is not on the list, create new room
        TAPRoomListModel *newRoomList = [TAPRoomListModel new];
        newRoomList.lastMessage = message;
        
        if (message.isHidden) {
            //Don't process last message that is hidden
            return;
        }
        
        if (![message.user.userID isEqualToString:[TAPChatManager sharedManager].activeUser.userID]) {
            //Message from other recipient, set unread as 1
            newRoomList.numberOfUnreadMessages = 1;
            
            BOOL hasMention = [TAPUtil isActiveUserMentionedWithMessage:message activeUser:[TAPDataManager getActiveUser]];
            if (hasMention) {
                newRoomList.numberOfUnreadMentions = 1;
            }
            else {
                newRoomList.numberOfUnreadMentions = 0;
            }
        }
        else {
            //Current user send new message, set unread to 0
            newRoomList.numberOfUnreadMessages = 0;
            newRoomList.numberOfUnreadMentions = 0;
        }
        
        [self insertRoomListToArrayAndDictionary:newRoomList atIndex:0];
        [self.roomListView.roomListTableView performBatchUpdates:^{
            //changing beginUpdates and endUpdates with this because of deprecation
            [self.roomListView.roomListTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
        } completion:^(BOOL finished) {
            [self.roomListView showNoChatsView:NO];
        }];
    }
    
    [self getAndUpdateNumberOfUnreadToDelegate];
}

- (void)updateCellDataAtIndexPath:(NSIndexPath *)indexPath updateUnreadBubble:(BOOL)updateUnreadBubble {
    if (indexPath.row >= [self.roomListArray count]) {
        return;
    }
    
    TAPRoomListTableViewCell *cell = [self.roomListView.roomListTableView cellForRowAtIndexPath:indexPath];
    TAPRoomListModel *roomList = [self.roomListArray objectAtIndex:indexPath.row];
    [cell setRoomListTableViewCellWithData:roomList updateUnreadBubble:updateUnreadBubble];
    
    //Check message draft
    NSString *draftMessage = [[TAPChatManager sharedManager] getMessageFromDraftWithRoomID:roomList.lastMessage.room.roomID];
    draftMessage = [TAPUtil nullToEmptyString:draftMessage];
    if (![draftMessage isEqualToString:@""]) {
        [cell showMessageDraftWithMessage:draftMessage];
    }
}

- (void)openNewChatViewController {
    TAPAddNewChatViewController *addNewChatViewController = [[TAPAddNewChatViewController alloc] init];
    addNewChatViewController.roomListViewController = self;
    addNewChatViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    addNewChatViewController.delegate = self;
    UINavigationController *addNewChatNavigationController = [[UINavigationController alloc] initWithRootViewController:addNewChatViewController];
    addNewChatNavigationController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:addNewChatNavigationController animated:YES completion:nil];
}

- (void)hideSetupViewWithDelay:(double)delayTime {
    [TAPUtil performBlock:^{
        [self.setupRoomListView showFirstLoadingView:NO withType:TAPSetupRoomListViewTypeSuccess];
    } afterDelay:delayTime];
}

- (void)reachabilityStatusChange:(NSNotification *)notification {
    if ([AFNetworkReachabilityManager sharedManager].reachable) {
        if (self.isNeedRefreshOnNetworkDown) {
            //Reload new data from API
            _isShouldNotLoadFromAPI = NO;
            [self viewLoadedSequence];
            
            _isNeedRefreshOnNetworkDown = NO;
            
        }
    }
    else {
        _isNeedRefreshOnNetworkDown = YES;
    }
}

- (void)showLoadingSetupView {
    [self.setupRoomListView showSetupViewWithType:TAPSetupRoomListViewTypeSettingUp];
    [self.setupRoomListView showFirstLoadingView:YES withType:TAPSetupRoomListViewTypeSettingUp];
}

- (void)clearAllData {
    [self.roomListArray removeAllObjects];
    [self.roomListDictionary removeAllObjects];
    [self.roomListView.roomListTableView reloadData];
}

- (void)getAndUpdateNumberOfUnreadToDelegate {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSInteger unreadRoomCount = 0;
        NSArray *unreadRoomArray = [self.unreadRoomIDs copy];
        for(TAPRoomListModel *roomList in self.roomListArray) {
            TAPMessageModel *selectedMessage = roomList.lastMessage;
            TAPRoomModel *room = selectedMessage.room;
            if(roomList.numberOfUnreadMessages > 0 || roomList.isMarkedAsUnread) {
                unreadRoomCount++;
            }
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //Send delegate to be used to client side, update to delegate after check unread database
            if ([[TapTalk sharedInstance].delegate respondsToSelector:@selector(tapTalkUnreadChatRoomBadgeCountUpdated:)]) {
                [[TapTalk sharedInstance].delegate tapTalkUnreadChatRoomBadgeCountUpdated:unreadRoomCount];
            }
        });
        
    });
}

- (void)checkUpdatedUserProfileWithMessage:(TAPMessageModel *)message {
    NSString *roomID = message.room.roomID;
    
    NSString *currentActiveUserID = [TAPChatManager sharedManager].activeUser.userID;
    currentActiveUserID = [TAPUtil nullToEmptyString:currentActiveUserID];
    NSString *constructedCurrentRoomID = [NSString stringWithFormat:@"%li-%li", (long)[currentActiveUserID integerValue], (long)[currentActiveUserID integerValue]];
    
    if ([roomID isEqualToString:constructedCurrentRoomID]) {
        //Update self profile
        [self checkAndUpdateActiveUserProfile];
    }
    else {
        //update user profile
        TAPRoomListModel *roomList = [self.roomListDictionary objectForKey:roomID];
        NSInteger cellRow = [self.roomListArray indexOfObject:roomList];
        NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:cellRow inSection:0];
        [self updateCellDataAtIndexPath:cellIndexPath updateUnreadBubble:NO];
    }
}

- (void)checkAndUpdateActiveUserProfile {
    NSString *profileImageURL = [TAPChatManager sharedManager].activeUser.imageURL.thumbnail;
    if (profileImageURL == nil || [profileImageURL isEqualToString:@""]) {
        TAPUserModel *currentActiveUser = [TAPDataManager getActiveUser];
        if (currentActiveUser.fullname == nil || [currentActiveUser.fullname isEqualToString:@""]) {
            self.leftBarInitialNameView.alpha = 0.0f;
            self.leftBarInitialNameButton.alpha = 0.0f;
            self.leftBarInitialNameButton.userInteractionEnabled = NO;
            self.profileImageView.alpha = 1.0f;
            self.profileImageView.image = [UIImage imageNamed:@"TAPIconDefaultAvatar" inBundle:[TAPUtil currentBundle] compatibleWithTraitCollection:nil];
        }
        else {
            self.leftBarInitialNameView.alpha = 1.0f;
            self.leftBarInitialNameButton.alpha = 1.0f;
            self.leftBarInitialNameButton.userInteractionEnabled = YES;
            self.profileImageView.alpha = 0.0f;
            self.leftBarInitialNameView.backgroundColor = [[TAPStyleManager sharedManager] getRandomDefaultAvatarBackgroundColorWithName:currentActiveUser.fullname];
            self.leftBarInitialNameLabel.text = [[TAPStyleManager sharedManager] getInitialsWithName:currentActiveUser.fullname isGroup:NO];
        }
    }
    else {
        self.leftBarInitialNameView.alpha = 0.0f;
        self.leftBarInitialNameButton.alpha = 0.0f;
        self.leftBarInitialNameButton.userInteractionEnabled = NO;
        self.profileImageView.alpha = 1.0f;
        [self.profileImageView setImageWithURLString:profileImageURL];
    }
}

- (void)hideSetupView {
    [self.setupRoomListView showFirstLoadingView:NO withType:TAPSetupRoomListViewTypeSuccess];
}

- (UIImage *)createImageFromView:(UIView *)view {
    //AS NOTE - THIS METHOD CONVERT UIVIEW INTO UIIMAGE
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0f);

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];;

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

- (UIView *)addedUIViewSwipeAction {
    //Create UIVIEW as you want view for Action Button
    NSString *descriptionActionString = @"";
    
    descriptionActionString = self.readUnreadStateString;
    
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 74.0f, 86.0f)];
    containerView.backgroundColor = [UIColor clearColor];
    
    UIImageView *iconImageview = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(containerView.frame) - 32.0f) / 2.0f, (CGRectGetHeight(containerView.frame) - 32.0f - 6.0f - 16.0f) / 2.0f, 32.0f, 32.0f)];
    iconImageview.contentMode = UIViewContentModeScaleAspectFit;
    iconImageview.backgroundColor = [UIColor clearColor];
    iconImageview.image = self.readUnreadStateImage;
    [containerView addSubview:iconImageview];
    
    UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, CGRectGetMaxY(iconImageview.frame) + 6.0f, CGRectGetWidth(containerView.frame), 16.0f)];
    descriptionLabel.text = descriptionActionString;
    descriptionLabel.textColor = [UIColor whiteColor]; //AS NOTE - default 793DA0
    UIFont *descriptionLabelFont = [[TAPStyleManager sharedManager] getComponentFontForType:TAPComponentFontRoomListTime];
    //descriptionLabel.font = descriptionLabelFont;
    descriptionLabel.textAlignment = NSTextAlignmentCenter;
    [containerView addSubview:descriptionLabel];
    
    return containerView;
}

- (void)callApiGetMarkedUnreadIDs{
    [TAPDataManager callAPIGetMarkedAsUnreadChatRoomList:^(NSArray <NSString *> *roomIDs){
        //handle pref
        [TAPDataManager setUnreadRoomIDs:roomIDs];
    } failure:^(NSError *error) {
    }];
}

@end