// // 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