//
//  HistoryViewController.m
//  DrivoMeter
//
//  Created by Mobi on 1/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "HistoryViewController.h"
#import <CoreData/CoreData.h>
#import "Database+Trips.h"
#import "Constants.h"
#import "HistoryViewCell.h"
#import "Trip.h"
#import "UITableViewCell+Extensions.h"
#import "HistoryDetailsViewController.h"
#import "Period.h"
#import "SelectPeriodViewController.h"

@interface HistoryViewController (Private)
- (void)filterButtonPressed;
@end
@implementation HistoryViewController

@synthesize tripsFetchedResultsController = tripsFetchedResultsController_;
@synthesize database = database_;
@synthesize currentPeriod = currentPeriod_;

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

- (void)didReceiveMemoryWarning
{
  // Releases the view if it doesn't have a superview.
  [super didReceiveMemoryWarning];
  
  // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
  [super viewDidLoad];
  if (currentPeriod_ == nil) {
    [self setCurrentPeriod:[[Period alloc] initWithPeriod:all]];
  }
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];  
  MSLog(@"viewWillAppear period %@", currentPeriod_);

  if (tripsFetchedResultsController_ == nil) {
    [self setTripsFetchedResultsController:[database_ fetchedResultsControllerForTripsInRangeFrom:currentPeriod_.beginningDate to:currentPeriod_.endDate]];
    
    [tripsFetchedResultsController_ setDelegate:self];
    
    NSError *error = nil;
    BOOL success = [tripsFetchedResultsController_ performFetch:&error];
    if (!success) {
      MSLog(@"fetch not success");
    }
    if (error != nil) {
      MSLog(@"fetch error: %@", error);
    }
    
    MSLog(@"fetched %d items", [[tripsFetchedResultsController_ fetchedObjects] count]);
    
    [self.tableView reloadData];
  }
  [currentPeriod_ setPeriodDates];
  [self updatePeriodTo:currentPeriod_];
  [self.navigationItem setTitle:NSLocalizedString(@"history.view.title", nil)];
  UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"button.back.title", nil) style:UIBarButtonItemStyleBordered target:nil action:nil];
  [backButton setTintColor:[UIColor orangeColor]];
  self.navigationItem.backBarButtonItem = backButton;
  [self.navigationItem setLeftBarButtonItem:self.editButtonItem];
  [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"button.title.delete", nil)];
  UIBarButtonItem *filterButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"history.view.filter.button.title", nil) 
                                                                   style:UIBarButtonItemStylePlain 
                                                                  target:self 
                                                                  action:@selector(filterButtonPressed)];
  [filterButton setTintColor:[UIColor orangeColor]];
  [self.navigationItem setRightBarButtonItem:filterButton];
}

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

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  // Return YES for supported orientations
  return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// 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_ deleteTrip:[tripsFetchedResultsController_ 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);
  }
}

#pragma mark - TableView 

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return 80.0;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"historyViewCell";
  
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [UITableViewCell loadCellFromXib:@"HistoryViewCell"];
  }
  
  Trip *trip = [tripsFetchedResultsController_ objectAtIndexPath:indexPath];
  [(HistoryViewCell *) cell fillWithTrip:trip];
  return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [self.tableView deselectRowAtIndexPath:indexPath animated:TRUE];
  
  Trip *trip = [tripsFetchedResultsController_ objectAtIndexPath:indexPath];
  HistoryDetailsViewController *controller = [[HistoryDetailsViewController alloc] init];
  [controller setDatabase:database_];
  [controller setTrip:trip];
  [self.navigationController pushViewController:controller animated:YES];
}


- (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)controllerDidChangeContent:(NSFetchedResultsController *)controller {
  [self.tableView endUpdates];
}

- (void)filterButtonPressed {
  SelectPeriodViewController *controller = [[SelectPeriodViewController alloc] init];
  [controller setSelectedPeriod:currentPeriod_];
  [controller setDelegate:self];
  [self.navigationController pushViewController:controller animated:YES];
}

- (void)updatePeriodTo:(Period *)newPeriod {
  [self setCurrentPeriod:newPeriod];
  [database_ updateFetchedResultsController:tripsFetchedResultsController_ withPeriod:newPeriod];
  NSError *error = nil;
  BOOL success = [tripsFetchedResultsController_ performFetch:&error];
  if (!success) {
    MSLog(@"fetch not success");
  }
  if (error != nil) {
    MSLog(@"fetch error: %@", error);
  }
  
  MSLog(@"fetched %d items", [[tripsFetchedResultsController_ fetchedObjects] count]);
  
  [self.tableView reloadData];
}

@end
