//
//  FavoritesViewController.m
//  DrivoMeter
//
//  Created by Triin Uudam on 4/26/12.
//  Copyright (c) 2012 Mobi Solutions OÜ. All rights reserved.
//

#import "FavoritesViewController.h"
#import "Database+Favorites.h"
#import "Constants.h"
#import "Favorite.h"
#import "AddFavoriteViewController.h"

@interface FavoritesViewController ()

@end

@implementation FavoritesViewController

@synthesize database = database_;
@synthesize favoritesFetchedResultsController = favoritesFetchedResultsController_;
@synthesize addFavoriteCell = addFavoriteCell_;
@synthesize selectFavoriteMode = selectFavoriteMode_;
@synthesize delegate = delegate_;

- (id)init {
  self = [super initWithNibName:@"FavoritesViewController" bundle:nil];
  if (self) {
    // Custom initialization
  }
  return self;
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  
}

- (void)viewWillAppear:(BOOL)animated {
  
  [self.navigationItem setTitle:NSLocalizedString(@"favorites.view.title", nil)];
  self.navigationItem.rightBarButtonItem = self.editButtonItem;
  [self.navigationItem.rightBarButtonItem setTitle:NSLocalizedString(@"button.title.delete", nil)];
  [addFavoriteCell_.textLabel setText:NSLocalizedString(@"favorites.view.add.new.title", nil)];
  if (favoritesFetchedResultsController_ == nil) {
    [self setFavoritesFetchedResultsController:[database_ fetchedResultsControllerForFavorites]];
    
    [favoritesFetchedResultsController_ setDelegate:self];
    
    NSError *error = nil;
    BOOL success = [favoritesFetchedResultsController_ performFetch:&error];
    if (!success) {
      MSLog(@"fetch not success");
    }
    if (error != nil) {
      MSLog(@"fetch error: %@", error);
    }
    
    MSLog(@"fetched %d items", [[favoritesFetchedResultsController_ fetchedObjects] count]);
    
    [self.tableView reloadData];
  }
}

- (void)viewDidUnload
{
  [super viewDidUnload];
  // Release any retained subviews of the main view.
  // e.g. self.myOutlet = nil;
}

- (void)dealloc {
  [favoritesFetchedResultsController_ setDelegate:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  if (section == 1) {
    return 1;
  }
  else {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[favoritesFetchedResultsController_ sections] objectAtIndex:0];
    return [sectionInfo numberOfObjects];
  }  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
  }
  if (indexPath.section == 1) {
    return addFavoriteCell_;
  } else {
    Favorite *favorite = [favoritesFetchedResultsController_ objectAtIndexPath:indexPath];
    NSString *isBusiness;
    if (favorite.isBusinessValue) {
      isBusiness = @"Ä";
    }
    else {
      isBusiness = @"E";
    }
    [cell.textLabel setText:[NSString stringWithFormat:@"%@ • %@", isBusiness, favorite.purpose]];
    [cell.detailTextLabel setText:[NSString stringWithFormat:@"%.1f km", favorite.distanceValue]];
    
    [cell.textLabel setTextColor:[UIColor darkGrayColor]];
    [cell.textLabel setFont:[UIFont systemFontOfSize:17.0]];
    [cell.detailTextLabel setTextColor:[UIColor darkGrayColor]];
    [cell.detailTextLabel setFont:[UIFont systemFontOfSize:17.0]];
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
  }  
  
  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.
  if (indexPath.section == 1) {
    return NO;
  }
  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
    [database_ deleteFavorite:[favoritesFetchedResultsController_ objectAtIndexPath:indexPath]];
  }   
  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
  }   
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  return NSLocalizedString(@"button.title.delete", nil);
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
  // Make sure you call super first
  [super setEditing:editing animated:animated];
  
  if (editing)
  {
    self.editButtonItem.title = NSLocalizedString(@"button.title.done", nil);
  }
  else
  {
    self.editButtonItem.title = NSLocalizedString(@"button.title.delete", nil);
  }
}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
  [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
  UITableView *tableView = self.tableView;
  
  switch (type) {
      
    case NSFetchedResultsChangeInsert:
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
      break;
    case NSFetchedResultsChangeDelete:
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
      break;
    case NSFetchedResultsChangeUpdate:
      [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
      break;
    case NSFetchedResultsChangeMove:
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
      break;
  }
}

- (void)controller:(NSFetchedResultsController *)controller
  didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex
     forChangeType:(NSFetchedResultsChangeType)type {
  switch (type) {
    case NSFetchedResultsChangeInsert:
      [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
      break;
    case NSFetchedResultsChangeDelete:
      [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
      break;
    case NSFetchedResultsChangeUpdate:
    case NSFetchedResultsChangeMove:
    default:
      MSLog(@"type %d not handled", type);
  }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
  [self.tableView endUpdates];
}


/*
 // 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 - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
  if (indexPath.section == 1) {
    AddFavoriteViewController *controller = [[AddFavoriteViewController alloc] init];
    [controller setDatabase:database_];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
    [self.navigationController presentModalViewController:navController animated:YES];
  }
  else {
    if (selectFavoriteMode_) {
      Favorite *favorite = [favoritesFetchedResultsController_ objectAtIndexPath:indexPath];
      [self.delegate updateWithFavorite:favorite];
      [self.navigationController popViewControllerAnimated:YES];
    }
  }  
}

@end
