summaryrefslogtreecommitdiff
path: root/Juick/MessagesViewController.m
blob: 19eebf44aaa0ba3083d6ce69da627f294d85ed8d (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
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
//
//  MasterViewController.m
//  Juick
//
//  Created by Vitaly Takmazov on 26.10.13.
//  Copyright (c) 2013 com.juick. All rights reserved.
//

#import "SWRevealViewController.h"

#import "MessagesViewController.h"

#import "MessageCell.h"

#import "Message.h"

#import "NSURL+PathParameters.h"

static NSString *CellIdentifier = @"MessageCell";

@interface MessagesViewController ();

@property(nonatomic, strong) NSMutableArray *messages;
@property(nonatomic, assign) Boolean dataLoading;
@property(nonatomic, strong) NSURL *url;

@end

@implementation MessagesViewController

- (id)initWithURL:(NSURL *)messagesURL
{
    self = [super init];
    if (self) {
        self.url = messagesURL;
    }
    return self;
}

- (void) refreshData:(UIRefreshControl *)refresh {
    [self.messages removeAllObjects];
    [self.tableView reloadData];
    
    NSArray *next = [Message pullNextFromURL:self.url];
    int64_t delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self.tableView beginUpdates];
        CGPoint offset = self.tableView.contentOffset;
        for (int i = 0; i < [next count]; i++) {
            [self.messages addObject:[next objectAtIndex:i]];
            [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
        [self.tableView setContentOffset:offset animated:NO];
        [self.tableView endUpdates];
        [refresh endRefreshing];
    });
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint pos = scrollView.contentOffset;
    CGFloat contentHeight = scrollView.contentSize.height - scrollView.contentSize.height / 3;
    if (pos.y >= contentHeight && !self.dataLoading) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.dataLoading = YES;
            Message * lastMessage = [self.messages lastObject];
            NSArray *next = [Message pullNextFromURL:[self.url URLByAppendingParameters:[NSDictionary dictionaryWithObjectsAndKeys:lastMessage.MID, @"before_mid", nil]]]; 
            int64_t delayInSeconds = 1.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.tableView beginUpdates];
                for (int i = 0; i < [next count]; i++) {
                    [self.messages addObject:[next objectAtIndex:i]];
                    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                }
                [self.tableView setContentOffset:pos animated:NO];
                [self.tableView endUpdates];
                self.dataLoading = NO;
            });
        });
        
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.dataLoading = NO;
    self.title = @"Discover";
    [self.view setBackgroundColor:[UIColor colorWithRed:238/255.0f green:238/255.0f blue:229/255.0f alpha:1.0f]];
    SWRevealViewController *revealController = [self revealViewController];
    [self.navigationController.navigationBar addGestureRecognizer:revealController.panGestureRecognizer];
    UIBarButtonItem *revealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"reveal-icon.png"]
                                                                         style:UIBarButtonItemStyleBordered target:revealController action:@selector(revealToggle:)];
    
    self.navigationItem.leftBarButtonItem = revealButtonItem;
    self.messages = [NSMutableArray array];
    UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
    [refresh addTarget:self action:@selector(refreshData:) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refresh;
    
    //UINib *cellNib = [UINib nibWithNibName:@"MessageCell" bundle:nil];
    //[self.tableView registerNib:cellNib forCellReuseIdentifier:@"MessageCell"];
    [self.tableView registerClass:[MessageCell class] forCellReuseIdentifier:CellIdentifier];    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(contentSizeCategoryChanged:)
                                                 name:UIContentSizeCategoryDidChangeNotification
                                               object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIContentSizeCategoryDidChangeNotification
                                                  object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)contentSizeCategoryChanged:(NSNotification *)notification
{
    [self.tableView reloadData];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell updateFonts];
    Message *msg = [_messages objectAtIndex:indexPath.row];
    [cell.avatar setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://i.juick.com/as/%@.png", msg.userID]]]]];
    cell.titleLabel.text = msg.user;
    cell.titleLabel.textColor = [UIColor colorWithRed:0 green:102/255.0f blue:153/255.0f alpha:1.0f];
    cell.bodyLabel.text =  msg.text;
    [cell setBackgroundColor:[UIColor whiteColor]];
    [cell setNeedsUpdateConstraints];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    [cell updateFonts];
    
    Message *msg = [_messages objectAtIndex:indexPath.row];
    [cell.avatar setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://i.juick.com/as/%@.png", msg.userID]]]]];
    cell.titleLabel.text = msg.user;
    cell.bodyLabel.text =  msg.text;
    
    cell.bodyLabel.preferredMaxLayoutWidth = tableView.bounds.size.width - (kLabelHorizontalInsets * 2.0f);
    
    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];
    [cell.contentView setNeedsLayout];
    [cell.contentView layoutIfNeeded];
    
    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100.0f;
}


@end