#import "RecipeDetailViewController.h"

@interface RecipeDetailViewController() <UITextFieldDelegate>

@end

@implementation RecipeDetailViewController

@synthesize tableHeaderView;
@synthesize recipe;
@synthesize titleLabel;
@synthesize descLabel;
@synthesize recipeImageView;

- (id)init
{
  if (!(self = [super initWithStyle:UITableViewStyleGrouped])) return nil;
  
  return self;
}

- (void)loadView
{
  [super loadView];
  if (tableHeaderView == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"DetailHeaderView" 
                                  owner:self 
                                options:nil];
    [[self tableView] setTableHeaderView:tableHeaderView];
    [[self tableView] setAllowsSelectionDuringEditing:YES];
  }
  [[self navigationItem] setRightBarButtonItem:[self editButtonItem]];
}

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  
  [self setTitle:[[self recipe] name]];
  [[self titleLabel] setText:[recipe name]];
  [[self descLabel] setText:[recipe desc]];
  [[self recipeImageView] setImage:[UIImage imageNamed:[recipe imagePath]]];
}

//START:setEditingAnimated
- (void)setEditing:(BOOL)editing animated:(BOOL)animated 
{
  [super setEditing:editing animated:animated];
  [self.navigationItem setHidesBackButton:editing animated:YES];
  
  [[self titleLabel] setEnabled:editing];
  
	if (editing) return;
  NSManagedObjectContext *context = recipe.managedObjectContext;
  NSError *error = nil;
  if ([context save:&error]) return;
  
  NSLog(@"save error %@, %@", error, [error userInfo]);
  exit(-1); // Fail
}
//END:setEditingAnimated

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField 
{
	if (textField == [self titleLabel]) {
    [recipe setName:[textField text]];
	}
	return YES;
}

#pragma mark -
#pragma mark UITableview Datasource / Delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{
  if ([indexPath section] == 1) return UITableViewCellEditingStyleDelete;
  return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView 
shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
  return [indexPath section] == 1;
}

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

- (NSInteger)tableView:(UITableView*)table 
 numberOfRowsInSection:(NSInteger)section 
{
  switch (section) {
    case 1:
      return [[recipe ingredients] count];
    default:
      return 1;
  }
}

- (NSString *)tableView:(UITableView *)tableView 
titleForHeaderInSection:(NSInteger)section 
{
  switch (section) {
    case 0:
      return @"Type";
    case 1:
      return @"Ingredients";
    default:
      return @"Description";
  }
}

- (UITableViewCell*)tableView:(UITableView*)tableView 
        cellForRowAtIndexPath:(NSIndexPath*)indexPath 
{
  id cell = nil;
  static NSString *cellIdentifier = @"Cell Identifier";
  static NSString *ingredIdentifier = @"Ingredient Identifier";
  NSString *identifier = ([indexPath section] == 1 ? 
                          ingredIdentifier : cellIdentifier);
  cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  if (!cell) {
    cell = [[[UITableViewCell alloc] initWithStyle:([indexPath section] == 1?UITableViewCellStyleSubtitle:UITableViewCellStyleDefault)
                                   reuseIdentifier:cellIdentifier] autorelease];
  }
  
  switch ([indexPath section]) {
    case 0:
      [[cell textLabel] setText:[recipe type]];
      [cell setAccessoryType:UITableViewCellAccessoryNone];
      [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
      break;
    case 1:
    {
      id ingredient = nil;
      ingredient = [[recipe sortedIngredients] objectAtIndex:[indexPath row]];
      [[cell textLabel] setText:[ingredient valueForKey:@"name"]];
      NSString *uom = [ingredient valueForKey:@"unitOfMeasure"];
      NSInteger quantity = [[ingredient valueForKey:@"quantity"] integerValue];
      NSString *subtitle = nil;
      subtitle = [NSString stringWithFormat:@"%u -- %@", quantity, uom];
      [[cell detailTextLabel] setText:subtitle];
      [cell setAccessoryType:UITableViewCellAccessoryNone];
      break;
    }
    case 2:
      [[cell textLabel] setText:@"Description"];
      [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
      [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
      break;
  }
  return cell;
}

@end
