summaryrefslogtreecommitdiff
path: root/Volta/Views/GraphViewController.m
blob: 44bf1037fa2dd0be7c894e77d0eeb81f09e91dab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
//
//  GraphViewController.m
//  Volta
//
//  Created by Ronny Fenrich on 2013-06-17.
//  Copyright (c) 2013 Decoder. All rights reserved.
//

#import "GraphViewController.h"
#import "StatsTabBarController.h"
#import "VoltaReading.h"


@interface GraphViewController ()<UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation GraphViewController



- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *resourcePath = [[[[NSBundle mainBundle] resourcePath] stringByReplacingOccurrencesOfString:@"/" withString:@"//"]
                              stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    NSString *markup = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"graph" ofType:@"html"]
                                                 encoding:NSUTF8StringEncoding
                                                    error:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.webView loadHTMLString:markup baseURL:[NSURL URLWithString:[NSString stringWithFormat:@"file:/%@//", resourcePath]]];
    });
}


- (void)viewDidUnload
{
    [self setWebView:nil];
    [super viewDidUnload];
}


- (void)viewWillDisappear
{
    if (self.webView.loading) {
        [self.webView stopLoading];
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self hideGradientBackground:self.webView];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM dd"];

    NSString *seriesA = @"";
    NSString *seriesB = @"";
    StatsTabBarController *parentTabBarController = (StatsTabBarController *)self.parentViewController;

    for (VoltaReading *reading in parentTabBarController.data.allValues)
    {
        float kWh = reading.usage / 1000.0f;
        float cost = reading.cost / 100000.0f;

        if (![seriesA isEmpty])
        {
            seriesA = [seriesA stringByAppendingString:@","];
        }
        if (![seriesB isEmpty])
        {
            seriesB = [seriesB stringByAppendingString:@","];
        }

        seriesA = [seriesA stringByAppendingString:[NSString stringWithFormat:@"['%@', %.2f]", [dateFormatter stringFromDate:reading.startDate], kWh]];
        seriesB = [seriesB stringByAppendingString:[NSString stringWithFormat:@"['%@', %.2f]", [dateFormatter stringFromDate:reading.startDate], cost]];
    }
    seriesA = [[@"[" stringByAppendingString:seriesA] stringByAppendingString:@"]"];
    seriesB = [[@"[" stringByAppendingString:seriesB] stringByAppendingString:@"]"];

    double delayInSeconds = 0.5;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"plotData(%@, %@)", seriesA, seriesB]];
    });

}


#pragma mark - Web View

- (void)hideGradientBackground:(UIView*)theView
{
    for (UIView * subview in theView.subviews)
    {
        if ([subview isKindOfClass:[UIImageView class]])
            subview.hidden = YES;

        [self hideGradientBackground:subview];
    }
}

- (void)webView:(UIWebView *)theWebView didFailLoadWithError:(NSError *)error
{
    // If the URLLoadingSystem cancelled the load don't show anything.
    NSString *errorUrl = [error.userInfo objectForKey:@"NSErrorFailingURLStringKey"];
    if (([error code] != NSURLErrorCancelled ) && ([[errorUrl uppercaseString] startsWith:@"HTTP"]))
    {
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Connection Error" message:@"We couldn't load the web page, please check your internet connection and try again."];
        [alert setCancelButtonWithTitle:@"Ok" block:nil];
        [alert show];
    }
}


- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)theRequest navigationType:(UIWebViewNavigationType)navigationType
{
//    if ([[theRequest.URL absoluteString] isEqual:@"flushd://ready"])
//    {
//        // pass in statistic data when webview is ready...
//        NSError *jsonError = nil;
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.statsController.userStats
//                                                           options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
//                                                             error:&jsonError];
//        if (jsonError)
//        {
//            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Error" message:@"Couldn't process statistic data. Please try again later."];
//            [alert setCancelButtonWithTitle:@"Ok" block:nil];
//            [alert show];
//            [self.spinner stopAnimating];
//            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
//        }
//        else
//        {
//            NSString *jsonStatsData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//            NSLog(@"%@", jsonStatsData);
//
//            // save world rank for later...
//            id usersWorldRankValue = [self.statsController.userStats valueForKeyPath:@"week.global_rank"];
//            if (usersWorldRankValue && !([usersWorldRankValue isEqual:[NSNull null]])) {
//                self.usersWorldRank = [usersWorldRankValue integerValue];
//            }
//
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"recalculateStats(%@)", jsonStatsData]];
//            });
//        }
//        return NO;
//    }
//    else
//        // webview is updated => present to the user now
//        if ([[theRequest.URL absoluteString] isEqual:@"flushd://loaded"])
//        {
//            // slide in webview from bottom of screen now
//            int finalWebViewPosition = self.webView.$y;
//            self.webView.$y = [[UIScreen mainScreen] applicationFrame].size.height + 20;
//            self.webView.hidden = NO;
//            self.shareButton.hidden = NO;
//
//            [UIView animateWithDuration:0.4
//                                  delay:0.6
//                                options:UIViewAnimationOptionCurveEaseOut
//                             animations:^{
//
//                                 self.webView.$y = finalWebViewPosition;
//
//                             } completion:^(BOOL finished) {
//
//                                 [self.spinner stopAnimating];
//                                 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
//                                 self.webView.$y = finalWebViewPosition;
//
//                                 // new badges? trigger javascript to show alert to the user
//                                 UIViewController *pController = self.parentViewController;
//                                 if ([pController isKindOfClass:[FlushdCustomTabBarController class]] && [pController respondsToSelector:@selector(setStatsBadge:)])
//                                 {
//                                     FlushdCustomTabBarController *aFlushdTabBarController = (FlushdCustomTabBarController *)pController;
//                                     if (aFlushdTabBarController.badgeLabel.tag > 0) {
//                                         dispatch_async(dispatch_get_main_queue(), ^{
//                                             [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showNewAchievementsPopup(%i)", aFlushdTabBarController.badgeLabel.tag]];
//                                         });
//
//                                         // remove badges after user is looking at the stats page...
//                                         [self removeStatsBadge];
//                                     }
//                                 }
//                             }];
//            return NO;
//        }
//


    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)theWebView
{
    // scroll to the top
    [self.webView.scrollView setContentOffset:CGPointMake(0, 0)];
}


- (void)webViewDidStartLoad:(UIWebView *)theWebView
{
}


@end