//
//  BeanCollectionListViewController.m
//  iBean
//
//  Created by Eddie Ehlin on 2013-01-03.
//  Copyright (c) 2013 Eddie Ehlin. All rights reserved.
//

#import "BeanCollectionListViewController.h"
#import "BeanCollectionInfoViewController.h"
#import "BeanCollectionExtractionViewController.h"
#import "BeanCollection.h"
#import "AppDelegate+Storage.h"

@interface BeanCollectionListViewController ()

@end

@implementation BeanCollectionListViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  NSLog(@"BeanCollectionListViewController view's loaded!");
  

  // Uncomment the following line to preserve selection between presentations.
  // self.clearsSelectionOnViewWillAppear = NO;
 
  // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
  // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void) viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  [self initViewController];
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
  if ([segue.identifier isEqualToString:@"NewBeanCollectionInfoSegue"])
  {
    //Tell the view controller that we'll be adding/handling a new bean collection
    BeanCollectionInfoViewController *infoViewController = (BeanCollectionInfoViewController *)[[segue.destinationViewController viewControllers] objectAtIndex:0];
    
    //Create new bean collection and pass it on to the next view controller!
    self.beanCollection = [(AppDelegate*) [[UIApplication sharedApplication] delegate] createBeanCollection];
    [infoViewController initWithModeAndBeanCollection:NO :self.beanCollection];
  }
  else if ([segue.identifier isEqualToString:@"BeanCollectionListBeanCollectionExtractionSegue"])
  {
    //Tell the view controller that we'll be handling/viewing an existing bean collection
    BeanCollectionExtractionViewController *extractionViewController = segue.destinationViewController;
    self.beanCollection = [self.beanCollections objectAtIndex:[self.tableView indexPathForSelectedRow].row];
    [extractionViewController initWithBeanCollection: self.beanCollection];
  }
}

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

#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 (we only have one section).
  return self.beanCollections.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"BeanCollectionCell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  
  //Configure the cell and set its title
  BeanCollection *currentCollection = [self.beanCollections objectAtIndex:indexPath.row];
  cell.textLabel.text = currentCollection.name;
    
  return cell;
}


// 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 (we want to be able to REMOVE though).
    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
    if (self.beanCollections != nil)
    {
      if ([(AppDelegate*) [[UIApplication sharedApplication] delegate] deleteObject:[self.beanCollections objectAtIndex:indexPath.row]] != nil)
      {
        NSLog(@"deleteObject returned an error when deleting bean collection!");
        UIAlertView *deleteErrorAlert = [[UIAlertView alloc]
                                         initWithTitle:@"Delete error!"
                                         message:[NSString stringWithFormat:@"Unable to delete bean collection:%@", [tableView cellForRowAtIndexPath:indexPath].textLabel.text]
                                         delegate:nil
                                         cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [deleteErrorAlert show];
        
      }
      else
      {
        //Reload our bean collections array from storage (since it is no longer consistent)
        self.beanCollections = [(AppDelegate*) [[UIApplication sharedApplication] delegate] getBeanCollections];
      }
    }
    [tableView deleteRowsAtIndexPaths:@[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
  }   
}

#pragma mark - Table view delegate

/*****************************************************
 Utility methods
 *****************************************************/
- (void) initViewController
{
  NSLog(@"BeanCollectionListViewController - initViewController");
#warning TODO - Test on real hw to see if we need to have conditional reloading (i.e.: only when new data has been added!)
  //Allocate edit's done button
  self.beanCollectionsListEditDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(toggleEditMode:)];
    
  //Load bean collections from core data storage
  self.beanCollections = [(AppDelegate*) [[UIApplication sharedApplication] delegate] getBeanCollections];
  if (self.beanCollections != nil)
  {
    [self.tableView reloadData];
  }
  
  //Reset editing state
  self.editing = NO;
}

/*****************************************************
 UI Actions
 *****************************************************/
#pragma mark - IBActions

- (void) toggleEditMode:(id)sender
{
  if (self.editing)
    self.navigationItem.leftBarButtonItem = self.beanCollectionsListEditButton;
  else
    self.navigationItem.leftBarButtonItem = self.beanCollectionsListEditDoneButton;
  
  [self setEditing:!self.editing animated:YES];
}

@end