summaryrefslogtreecommitdiff
path: root/Juick/ViewControllers/ChatViewController.m
blob: 0de3d2af0d7d7be9607e7cf724a4ac20a67e2b12 (plain) (blame)
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
//
//  ChatViewController.m
//  Juick
//
//  Created by Vitaly Takmazov on 04/03/2018.
//  Copyright © 2018 com.juick. All rights reserved.
//

#import "ChatViewController.h"
#import "BubbleMessageCell.h"
#import "APIClient.h"

@interface ChatViewController ()

@property (nonatomic, readwrite, retain) UIView *inputAccessoryView;
@property (nonatomic, strong) NSString *me;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.visibleViewController setTitle:self.uname];
    [self.tableView registerNib:[UINib nibWithNibName:@"BubbleMessageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"bubbleMessageCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
    self.tableView.allowsSelection = NO;
    self.me = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.username"];
    [self reloadChat];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    self.refreshControl = [UIRefreshControl new];
    [self.refreshControl addTarget:self action:@selector(reloadChat) forControlEvents:UIControlEventValueChanged];
    [self addObserver:self forKeyPath:@"uname" options:0 context:nil];
}

-(void) reloadChat {
    self.messages = [NSMutableArray array];
    [self.tableView reloadData];
    [[APIClient sharedClient] fetchChatWithUser:self.uname callback:^(NSArray *messages, NSError *err) {
        if (err == nil) {
            [self.messages addObjectsFromArray:[[messages reverseObjectEnumerator] allObjects]];
            NSMutableArray *indexPaths = [NSMutableArray new];
            for (NSUInteger index = 0; index < [messages count]; index++) {
                [indexPaths addObject:[NSIndexPath indexPathForRow:index inSection: 0]];
            }
            [self.tableView beginUpdates];
            [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:YES];
            [self.tableView endUpdates];
            NSInteger messagesCount = [self.messages count];
            if (messagesCount > 0) {
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
        }
        [self.refreshControl endRefreshing];
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BubbleMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bubbleMessageCell" forIndexPath:indexPath];
    Message *message = [self.messages objectAtIndex:indexPath.row];
    [cell configureWithMessage:message isMe:[self.me isEqualToString:message.user.uname]];
    return cell;
}

-(BOOL) canBecomeFirstResponder {
    return YES;
}

- (UIView *) inputAccessoryView {
    if (!_inputAccessoryView) {
        PHFComposeBarView *composeView = [[PHFComposeBarView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - PHFComposeBarViewInitialHeight, self.view.bounds.size.width, PHFComposeBarViewInitialHeight)];
        composeView.delegate = self;
        [composeView.bottomAnchor constraintEqualToSystemSpacingBelowAnchor:self.view.safeAreaLayoutGuide.bottomAnchor multiplier:1.0f];
        composeView.maxLinesCount = 4;
        _inputAccessoryView = composeView;
    }
    return _inputAccessoryView;
}

-(void) keyboardWillChangeFrame:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    if (userInfo) {
        CGRect beginFrame = [userInfo [UIKeyboardFrameBeginUserInfoKey] CGRectValue];
        CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat delta = endFrame.origin.y - beginFrame.origin.y;
        CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
        UIViewAnimationCurve animationCurve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
        [UIView animateWithDuration:duration delay:0 options:(animationCurve << 16) animations:^{
            self.tableView.contentOffset = CGPointMake(0, self.tableView.contentOffset.y - delta);
        } completion:nil];
    }
}

-(void) composeBarViewDidPressButton:(PHFComposeBarView *)composeBarView {
    [[APIClient sharedClient] postPMToUser:self.uname text:composeBarView.text result:^(NSError *err) {
        if (!err) {
            NSLog(@"Success!");
            [composeBarView becomeFirstResponder];
            [composeBarView setText:nil animated:NO];
            [self reloadChat];
        }
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    [self reloadChat];
}

@end