ScanBookViewController.m 12.9 KB
Newer Older
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
//
//  ScanBookViewController.m
//  PLUCdraft
//
//  Created by Alexander W. Moore on 2/3/15.
//  Copyright (c) 2015 Alexander W. Moore. All rights reserved.
//


#import "ScanBookViewController.h"
#import "SectionViewController.h"
#import "GlobalWebController.h"

static int BOOK_ID_LENGTH = 14;

@interface ScanBookViewController ()
//@property (weak, nonatomic) IBOutlet UITextField *txtBookID;
@property (weak, nonatomic) IBOutlet UIImageView *imgCheck;
@property (weak, nonatomic) IBOutlet UIImageView *imgX;
@property (weak, nonatomic) IBOutlet UILabel *lblSection;

@property NSMutableArray *scannedBookList;
@property NSMutableArray *idList;
@property NSMutableArray *callNumList;
@property NSMutableArray *titleList;
- (IBAction)txtChange:(id)sender;



@end

@implementation ScanBookViewController

@synthesize session;
@synthesize lblSection;
@synthesize txtBookID;
@synthesize imgCheck;
@synthesize imgX;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    lblSection.text = session.section;
    //[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self.view action:@selector(endEditing:)]];
    
    // SEND SESSION TO RTI
    
    //self.navigationItem.hidesBackButton = YES;
    self.scannedBookList = [[NSMutableArray alloc] init];
    self.idList = [[NSMutableArray alloc] init];
    self.callNumList = [[NSMutableArray alloc] init];
    self.titleList = [[NSMutableArray alloc] init];
    
    self.scannedBookTableView.delegate = self;
    self.scannedBookTableView.dataSource = self;
    [self.scannedBookTableView reloadData];
    
    
    //For testing
    //[self.webview loadRequest:[NSURLRequest requestWithURL: [NSURL
    //                                                         URLWithString:@"file:///Users/plucseniordesign/Desktop/RTIScan2/RTIScan2.html"]]];
}

-(void) viewDidAppear:(BOOL)animated {
    //NSLog(@"viewDidAppear, 2nd view controller");
    //GlobalWebController *globalWeb = [GlobalWebController getInstance];
    //self.webview = globalWeb.web;
    //[self.test_view setDelegate:self];
    //self.test_view = globalWeb.web;
    
    //[self.view addSubview:self.webview];
    //[self.view addSubview:self.test_view];
    //[self.test_view setScalesPageToFit:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [super webViewDidFinishLoad:webView];
    NSURLRequest *currentRequest = [webView request];
    NSURL *currentURL = [currentRequest URL];
    NSLog(@"2: Current URL is %@", currentURL.absoluteString);

    
}

- (void)extractInformation:(NSString *)scannedBooks {

    //Clear lists
    [self.idList removeAllObjects];
    [self.callNumList removeAllObjects];
    [self.titleList removeAllObjects];
    [self.scannedBookList removeAllObjects];
    
    //Extract book ID
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\"id\"\\:\"([0-9]*)\"\\," options:0 error: Nil];
    NSArray *rangeList = [regex matchesInString:scannedBooks options:0 range:NSMakeRange(0, [scannedBooks length])];
    NSString *idNum;
    for(NSTextCheckingResult *range in rangeList) {
        idNum = [scannedBooks substringWithRange:[range rangeAtIndex:1]];
        NSLog(idNum);
        [self.idList addObject:idNum];
    }
    //Extract book call number
    regex = [NSRegularExpression regularExpressionWithPattern:@"\"callnum\"\\:\"([0-9a-zA-Z\\.]*)\"\\," options:0 error: Nil];
    rangeList = [regex matchesInString:scannedBooks options:0 range:NSMakeRange(0, [scannedBooks length])];
    NSString *callNum;
    for(NSTextCheckingResult *range in rangeList) {
        callNum = [scannedBooks substringWithRange:[range rangeAtIndex:1]];
        NSLog(callNum);
        [self.callNumList addObject:callNum];
    }
    //Extract book title
    regex = [NSRegularExpression regularExpressionWithPattern:@"\"title\"\\:\"(.*)\"\\}" options:0 error: Nil];
    rangeList = [regex matchesInString:scannedBooks options:0 range:NSMakeRange(0, [scannedBooks length])];
    NSString *title;
    for(NSTextCheckingResult *range in rangeList) {
        title = [scannedBooks substringWithRange:[range rangeAtIndex:1]];
        NSLog(title);
        [self.titleList addObject:[scannedBooks substringWithRange:[range rangeAtIndex:1]]];
    }
    
    //NSLog(@"%@, %@, %@", [self.idList objectAtIndex:0], [self.callNumList objectAtIndex:0], [self.titleList objectAtIndex:0]);
    //Populate table view
    //NSLog(@"num scanned books = %lu", (unsigned long)[self.idList count]);
    for(int i = 0; i < [self.idList count]; i++) {
        //NSLog(@"%@, %@, %@", [self.idList objectAtIndex:i], [self.callNumList objectAtIndex:i], [self.titleList objectAtIndex:i]);
        [self.scannedBookList addObject:[self.idList objectAtIndex:i]];
    }
    //NSLog(@"Got here");
    [self.scannedBookTableView reloadData];
    

}

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

//allow app to flip to upside down
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait)
        return YES;
    if (toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        return YES;
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        return NO;
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
        return NO;
    return NO; // Unknown value
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // Return the number of rows in the section.
    return [self.idList count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListPrototypeCell" forIndexPath:indexPath];
    
    // Configure the cell...
    NSString *scannedBook = [self.scannedBookList objectAtIndex:indexPath.row];
    cell.textLabel.text = scannedBook;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *bookID = [self.idList objectAtIndex:indexPath.row];
    NSString *callNum = [self.callNumList objectAtIndex:indexPath.row];
    NSString *title = [self.titleList objectAtIndex:indexPath.row];
    NSString *message = [NSString stringWithFormat:@"Book ID: %@\nCall Number: %@\nTitle: %@\n", bookID, callNum, title];
    UIAlertView *messageAlert = [[UIAlertView alloc]
                                 initWithTitle:@"Book details" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    // Display Alert Message
    [messageAlert show];
    
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:NO];
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    if([segue.destinationViewController isKindOfClass:[SectionViewController class]]) {
    // TELL OCI TO END SESSION aka exit out of page
    }
    
    
}


-(void) changeCheckImage {
    imgCheck.image = [UIImage imageNamed:@"greencheck.png"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        sleep(1);
        //do other stuff
        dispatch_async(dispatch_get_main_queue(), ^{
            imgCheck.image = [UIImage imageNamed:@"greycheck2.png"];
            txtBookID.text = @"";
        });  
    });
}

-(void) changeXImage {
    imgX.image = [UIImage imageNamed:@"redx.png"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        sleep(1);
        //do other stuff
        dispatch_async(dispatch_get_main_queue(), ^{
            imgX.image = [UIImage imageNamed:@"greyx2.png"];
            txtBookID.text = @"";
        });
    });
}

- (void) barcodeTextChanged {
    NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if(self.txtBookID.text.length == BOOK_ID_LENGTH) {  //string is proper length
        if([self.txtBookID.text rangeOfCharacterFromSet:notDigits].location == NSNotFound) {  //string is numeric
            // SEND BOOK ID TO RTI
            NSString *barcode = self.txtBookID.text;
            
            NSString *stringStart = @"var code = '";
            NSString *stringEnd = @"';";
            NSString *newString = [stringStart stringByAppendingString:barcode];
            NSString *inputCode = [newString stringByAppendingString:stringEnd];
            
            NSString *scanPath =
            [[NSBundle mainBundle] pathForResource:@"ScanBarcode" ofType:@"js"];
            NSString *scan = [NSString stringWithContentsOfFile:scanPath
                                                       encoding:NSUTF8StringEncoding
                                                          error:nil];
            
            [self.webview stringByEvaluatingJavaScriptFromString:inputCode];
            [self.webview stringByEvaluatingJavaScriptFromString:scan];
            //            //randomly generate errors
            //            int random = arc4random() % 10;
            //            if(random < 5) {
            //                //green check
            //                [self changeCheckImage];
            //
            //            } else {
            //                //red x
            //                [self changeXImage];
            //            }
            NSLog(@"ID accepted");
            self.view.backgroundColor = [UIColor greenColor];
            [UIView animateWithDuration:1.0 animations:^{
                self.view.backgroundColor = [UIColor whiteColor];
            }];
            [self.txtBookID setText:@""];
            // Get scanned codes - Testing GetScanned
            NSString *getScanPath =
            [[NSBundle mainBundle] pathForResource:@"GetScanned" ofType:@"js"];
            NSString *getScan = [NSString stringWithContentsOfFile:getScanPath
                                                          encoding:NSUTF8StringEncoding
                                                             error:nil];
            
            NSString *scanned =
            [self.webview stringByEvaluatingJavaScriptFromString:getScan];
            //self.bookLog.text = scanned;
            NSLog(@"%@", scanned);
            //    UIAlertView *previousScan =
            //    [[UIAlertView alloc] initWithTitle:@"Previous Scans"
            //                               message:scanned
            //                              delegate:self
            //                     cancelButtonTitle:@"OK"
            //                     otherButtonTitles:nil];
            //
            //    [previousScan show];
            [self extractInformation:scanned];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid Book ID" message:@"Book ID must be numeric" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
    } else {
        //if not 14 digits
        //UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid Book ID" message:@"Book ID improper length" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        //[alert show];
    }
}

//31172001492867
- (IBAction)txtChange:(id)sender {
    [self barcodeTextChanged];
}

- (void)decoderDataReceived:(NSString *)data {
    [super decoderDataReceived:data];
    [self barcodeTextChanged];
}

- (IBAction)clickedFinish:(id)sender {
    NSString *path =
    [[NSBundle mainBundle] pathForResource:@"WhatPage" ofType:@"js"];
    NSString *content = [NSString stringWithContentsOfFile:path
                                                  encoding:NSUTF8StringEncoding
                                                     error:nil];
    
    NSString *page =
    [self.webview stringByEvaluatingJavaScriptFromString:content];
    NSLog(@"PAGE NUMBER IS: %@\n", page);
    
    // Test FinishScan
    if ([page isEqual:@"2"]) {  // Scan Page
        NSString *finishPath =
        [[NSBundle mainBundle] pathForResource:@"FinishScan" ofType:@"js"];
        NSString *finish = [NSString stringWithContentsOfFile:finishPath
                                                     encoding:NSUTF8StringEncoding
                                                        error:nil];
        
        NSString *isFinished =
        [self.webview stringByEvaluatingJavaScriptFromString:finish];
        if ([isFinished isEqual:@"-1"]) {
        } else {
            NSLog(@"FINISHED NOT FAILED\n");
        }
    }
}

//- (void)decoderDataReceived:(NSString *)data {
//    [super decoderDataReceived:data];
//    [self textChange];
//}



@end