// // SourcesEditViewController.m // PicCast // // Created by Matthew Handler on 4/20/11. // Copyright 2011 Earl Industries. All rights reserved. // #import "SourcesEditViewController.h" #import "SourcesEditViewCell.h" #import "CJSONDeserializer.h" #import "PicCastAppDelegate.h" #import "FMDatabase.h" #import "FMResultSet.h" #import "Source.h" @interface MyButton : UISwitch { NSIndexPath *indexPath; } @property (nonatomic, retain) NSIndexPath *indexPath; @end @implementation MyButton @synthesize indexPath; @end @implementation SourcesEditViewController @synthesize delegate, tableView; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; self.tableView.rowHeight = 44; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; //NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; sectionDictionary = [[[SectionDictionary alloc] init] retain]; db = [[FMDatabase databaseWithPath:[PicCastAppDelegate getDatabasePath]] retain]; [db setShouldCacheStatements:NO]; //[db setTraceExecution:true]; //[db setLogsErrors:true]; [self loadSourcesFromDb]; _receivedData = [[NSMutableData data] retain]; NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://piccast.memeschemes.com/json/feeds/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; if ([NSURLConnection connectionWithRequest:theRequest delegate:self]) { [_receivedData setLength:0]; } else { //[MBProgressHUD hideHUDForView:self.view animated:YES]; [PicCastAppDelegate prompt:@"Error" withMessage:@"No internet connection" andButtonTitle:@"shucks" withDelegate:self]; } //[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"haveSearched"]; } - (void) loadSourcesFromDb { [db open]; FMResultSet *result = [db executeQuery:@"SELECT * FROM sources"]; while ([result next]) { Source *source = [Source initFromDatabaseRow:result]; [sectionDictionary appendObject:source forKey:source.category]; } [db close]; } - (IBAction)done:(id)sender { // NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; // [prefs setObject:[self getUserGenderString] forKey:@"userGender"]; // [prefs setObject:[self getHeetGenderString] forKey:@"heetGender"]; // [prefs synchronize]; [self.delegate sourcesEditViewControllerDidFinish:self]; } /* - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } */ /* - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ #pragma mark - #pragma mark custom sheeyit - (void) addSourcesFromJson:(NSData *)data { NSError *theError = nil; id dictionary = [[CJSONDeserializer deserializer] deserialize:(NSData *)data error:&theError]; NSArray *array = [dictionary objectForKey:@"list"]; //NSLog(@"class: %@", [array class]); [db open]; for (NSDictionary *obj in array) { //NSLog(@"foreign key: %d", [obj objectForKey:@"id"]); FMResultSet *result = [db executeQuery:@"SELECT * FROM sources WHERE foreignId = ?", [obj objectForKey:@"id"]]; if (![result next]) { //NSLog(@"found source"); Source *source = [Source initWithJsonObject:obj]; [sectionDictionary appendObject:source forKey:source.category]; [db beginTransaction]; [source serializeToDb:db]; [db commit]; } [result close]; } [db close]; } #pragma mark - #pragma mark url response - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [_receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [_receivedData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //[_receivedData release]; //[MBProgressHUD hideHUDForView:self.view animated:YES]; [PicCastAppDelegate prompt:@"Error" withMessage:[error localizedDescription] andButtonTitle:@"Aww man..." withDelegate:self]; //[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // NSString *json = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding]; // [_tableData removeAllObjects]; // [_tableData addObjectsFromArray:[[json JSONValue] objectForKey:@"results"]]; // [json release]; // // if ([_tableData count] > 0) { // [tableView reloadData]; // [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; // self.tableView.allowsSelection = YES; // self.tableView.scrollEnabled = YES; // } //[MBProgressHUD hideHUDForView:self.view animated:YES]; [self addSourcesFromJson:_receivedData]; //[_receivedData release]; [tableView reloadData]; } #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return [sectionDictionary count]; } // // - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [[sectionDictionary objectForIndex:section] count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [sectionDictionary keyForIndex:section]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"cell"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { // NSArray *tmpCell = [[NSBundle mainBundle] loadNibNamed:@"TopicTableViewCell" owner:self options:nil]; // // for (id currentObj in tmpCell) { // if ([currentObj isKindOfClass:[TopicTableViewCell class]]) { // cell = (TopicTableViewCell *)currentObj; // [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; // // UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease]; // [cell addSubview:mySwitch]; // cell.accessoryView = mySwitch; // // //cell.accessoryView = cell.switcher; // break; // } // } cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell... [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; Source *source = [[sectionDictionary objectForIndex:indexPath.section] objectAtIndex:indexPath.row]; //[cell setText:source.title]; [cell.textLabel setText:source.title]; MyButton *mySwitch = [[[MyButton alloc] initWithFrame:CGRectZero] autorelease]; if (source.subscribed) [mySwitch setOn:true]; mySwitch.indexPath = indexPath; [mySwitch addTarget:self action:@selector(switchedOnOff:) forControlEvents:UIControlEventValueChanged]; [cell addSubview:mySwitch]; cell.accessoryView = mySwitch; return cell; } - (void) switchedOnOff:(id)sender { // method is sent after switch actually gets switched, so the state is what we want it to be MyButton *switcher = (MyButton *)sender; NSIndexPath *indexPath = switcher.indexPath; NSNumber *foreignId = [[[sectionDictionary objectForIndex:indexPath.section] objectAtIndex:indexPath.row] foreignId]; NSLog(@"number %@", foreignId); [db open]; [db beginTransaction]; [db executeUpdate:@"UPDATE sources SET subscribed = ? WHERE foreignId = ?", [NSNumber numberWithInt:(switcher.on ? 1 : 0)], foreignId]; [db commit]; [db close]; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source. [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. /* <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil]; // ... // Pass the selected object to the new view controller. [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; */ } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc. that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)dealloc { [db release]; [sectionDictionary release]; [_receivedData release]; [super dealloc]; } @end