//
//  HistoryDetailsViewController.m
//  DrivoMeter
//
//  Created by Triin Uudam on 3/17/12.
//  Copyright (c) 2012 Mobi Solutions OÜ. All rights reserved.
//

#import "HistoryDetailsViewController.h"
#import "Trip.h"
#import "NSDate+Extensions.h"
#import "TextFieldCell.h"
#import "UITableViewCell+Extensions.h"
#import "Constants.h"
#import "Database.h"
#import "Database+Favorites.h"
#import "Favorite.h"

#define kRowIsBusiness       0
#define kRowDate             1
#define kRowPurpose          2
#define kRowDistance         3
#define kRowOdomBegin        4
#define kRowOdomEnd          5
#define kRowAddToFav         6

@interface HistoryDetailsViewController ()

- (void)showPickerOnView:(UIView *)view;
- (void)hidePickerFromView:(UIView *)view;
- (void)saveButtonPressed;
- (void)updateBusinessValue;
- (void)updateFavorite;

@end

@implementation HistoryDetailsViewController

@synthesize trip = trip_;
@synthesize database = database_;
@synthesize dateField = dateField_;
@synthesize distanceField = distanceField_;
@synthesize odomBeginField = odomBeginField_;
@synthesize odomEndField = odomEndField_;
@synthesize purposeField = purposeField_;
@synthesize pickerView = pickerView_;
@synthesize datePicker = datePicker_;
@synthesize doneButton = doneButton_;
@synthesize businessCell = businessCell_;
@synthesize isBusiness = isBusiness_;

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

- (void)viewDidLoad
{
  [super viewDidLoad];
  
  // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  
  [self.navigationItem setTitle:NSLocalizedString(@"history.details.view.title", nil)];
  [doneButton_ setTitle:NSLocalizedString(@"picker.view.done.button.title", nil)];
  UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"button.title.save", nil) 
                                                                 style:UIBarButtonItemStylePlain 
                                                                target:self 
                                                                action:@selector(saveButtonPressed)];
  [self.navigationItem setRightBarButtonItem:saveButton];
  [self setIsBusiness:trip_.isBusinessValue];
}

- (void)viewDidDisappear:(BOOL)animated {
  [super viewDidDisappear:animated];
  [self.navigationController popViewControllerAnimated:NO];
}

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

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

#pragma mark - TableView 

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"historyViewCell";
  
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [UITableViewCell loadCellFromXib:@"TextFieldCell"];
  }
  
  switch (indexPath.row) {
    case kRowIsBusiness:
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
      [cell setBackgroundColor:[UIColor clearColor]];
      [cell.textLabel setTextColor:[UIColor darkGrayColor]];
      [cell.textLabel setText:(trip_.isBusinessValue ? NSLocalizedString(@"history.details.view.business.travel.label", nil) : NSLocalizedString(@"history.details.view.private.travel.label", nil))];
      [self setBusinessCell:cell];
      break;
    case kRowPurpose:
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"add.trip.view.purpose.title", nil)];
      [[(TextFieldCell *)cell textField] setText:trip_.purpose];
      [self setPurposeField:[(TextFieldCell *)cell textField]];
      [purposeField_ setDelegate:self];
      break;
    case kRowDate: {
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"history.details.view.date.label", nil)];
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      [dateFormatter setDateFormat:@"dd.MM.yyyy"];
      [[(TextFieldCell *)cell textField] setText:[dateFormatter stringFromDate:trip_.beginDate]];
      [self setDateField:[(TextFieldCell *)cell textField]];
      [dateField_ setDelegate:self];
      [dateField_ setUserInteractionEnabled:NO];
      break;
    }
    case kRowDistance: {
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"history.details.view.distance.label", nil)];
      [[(TextFieldCell *)cell textField] setText:[NSString stringWithFormat:@"%.1f", trip_.distanceValue]];
      [self setDistanceField:[(TextFieldCell *)cell textField]];
      [distanceField_ setDelegate:self];
      break;
    }
    case kRowOdomBegin: {
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"history.details.view.odometer.begin.label" , nil)];
      [[(TextFieldCell *)cell textField] setText:[NSString stringWithFormat:@"%.1f", trip_.beginStateValue]];
      [self setOdomBeginField:[(TextFieldCell *)cell textField]];
      [odomBeginField_ setDelegate:self];
      
      break;
    }
    case kRowOdomEnd: {
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"history.details.view.odometer.end.label" , nil)];
      [[(TextFieldCell *)cell textField] setText:[NSString stringWithFormat:@"%.1f", trip_.endStateValue]];
      [self setOdomEndField:[(TextFieldCell *)cell textField]];
      [[(TextFieldCell *)cell textField] setReturnKeyType:UIReturnKeyDone];
      [odomEndField_ setDelegate:self];
      break;
    }
    case kRowAddToFav: {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      [cell.textLabel setText:(trip_.favorite ? NSLocalizedString(@"history.details.view.favorites.remove.title", nil) : NSLocalizedString(@"history.details.view.favorites.add.title", nil))];
      [cell setBackgroundColor:[UIColor clearColor]];
      [cell.textLabel setFont:[UIFont systemFontOfSize:17.0]];
      [cell.textLabel setTextColor:[UIColor darkGrayColor]];
    }
    default:
      break;
  }
  
  [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
  return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
  
  if (indexPath.row != 2) {
    [self hidePickerFromView:self.view];
  }
  
  switch (indexPath.row) {
    case kRowIsBusiness:
      [self updateBusinessValue];
      break;
    case kRowPurpose:
      [purposeField_ becomeFirstResponder];
      break;
    case kRowDate:
      [self showPickerOnView:self.view];
      break;
    case kRowDistance:     
      [distanceField_ becomeFirstResponder];
      break;
    case kRowOdomBegin:
      [odomBeginField_ becomeFirstResponder];
      break;
    case kRowOdomEnd:
      [odomEndField_ becomeFirstResponder];
      break; 
    case kRowAddToFav:
      [self updateFavorite];
      [self.tableView reloadData];
    default:
      break;
  }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
  if (textField != dateField_) {
    [self hidePickerFromView:self.view];
  }
  else if (textField == dateField_) {
    //TODO Triin check why this doesnt work
    [distanceField_ resignFirstResponder];
    [odomEndField_ resignFirstResponder];
    [odomBeginField_ resignFirstResponder];
    [purposeField_ resignFirstResponder];
  }
  return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  
  if (textField == distanceField_) {
    [odomBeginField_ becomeFirstResponder];
    [odomEndField_ setText:[NSString stringWithFormat:@"%.1f", [odomBeginField_.text doubleValue] + [distanceField_.text doubleValue]]];
  }
  else if (textField == purposeField_) {
    [purposeField_ resignFirstResponder];
    [distanceField_ becomeFirstResponder];
  }
  else if (textField == odomBeginField_) {
    [odomEndField_ becomeFirstResponder];
    [odomEndField_ setText:[NSString stringWithFormat:@"%.1f", [odomBeginField_.text doubleValue] + [distanceField_.text doubleValue]]];
  }
  else if (textField == odomEndField_) {
    [odomBeginField_ setText:[NSString stringWithFormat:@"%.1f", [odomEndField_.text doubleValue] - [distanceField_.text doubleValue]]];
    [odomEndField_ resignFirstResponder];
  }
  
  return YES;
}

- (void)showPickerOnView:(UIView *)view {
  [pickerView_ setFrame:CGRectMake(view.frame.origin.x,
                                   view.window.frame.origin.y + view.window.frame.size.height,
                                   pickerView_.frame.size.width,
                                   pickerView_.frame.size.height)];
  [UIView commitAnimations];
  [view addSubview:pickerView_];
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.3];
  [view bringSubviewToFront:pickerView_];
  [pickerView_ setFrame:CGRectMake(view.frame.origin.x,
                                   view.frame.size.height - pickerView_.frame.size.height,
                                   pickerView_.frame.size.width,
                                   pickerView_.frame.size.height)];
  [UIView commitAnimations];
}

- (void)hidePickerFromView:(UIView *)view {
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.3];
  [pickerView_ setFrame:CGRectMake(view.frame.origin.x,
                                   view.window.frame.origin.y + view.window.frame.size.height,
                                   pickerView_.frame.size.width,
                                   pickerView_.frame.size.height)];
  [UIView commitAnimations];
}

- (IBAction)displayDate:(id)sender {
  NSDate *selected = [datePicker_ date];
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateStyle:NSDateFormatterMediumStyle];
  NSString *date = [formatter stringFromDate:selected];
  [dateField_ setText:date];
}

- (void)doneButtonPressed:(id)sender {
  [self hidePickerFromView:self.view];
}

- (void)saveButtonPressed {
  UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"history.details.view.save.changes.title", nil) 
                                                           delegate:self 
                                                  cancelButtonTitle:NSLocalizedString(@"button.title.cancel", nil) 
                                             destructiveButtonTitle:nil 
                                                  otherButtonTitles:NSLocalizedString(@"button.title.save", nil), nil];
  [actionSheet showFromTabBar:self.tabBarController.tabBar];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (buttonIndex == 0) {
    [TestFlight passCheckpoint:@"save trip details via history details view"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setDateFormat:@"dd.MM.yyyy"];
    NSDate *beginDate = [formatter dateFromString:dateField_.text];
    [trip_ setBeginDate:beginDate];
    [trip_ setPurpose:purposeField_.text];
    [trip_ setDistanceValue:[distanceField_.text doubleValue]];
    [trip_ setBeginStateValue:[odomBeginField_.text doubleValue]];
    [trip_ setEndStateValue:[odomEndField_.text doubleValue]];
    [trip_ setIsBusinessValue:isBusiness_];
    if (trip_.favorite) {
      [trip_ setFavorite:nil];
    }
    [database_ saveContext];
    [self.navigationController popViewControllerAnimated:YES];
  } else {
    [self.navigationController popViewControllerAnimated:YES];
  }
}

- (void)updateBusinessValue {
  [TestFlight passCheckpoint:@"change business value in history details"];
  [self setIsBusiness:(isBusiness_ ? NO : YES)];
  [businessCell_.textLabel setText:(isBusiness_ ? NSLocalizedString(@"history.details.view.business.travel.label", nil) : NSLocalizedString(@"history.details.view.private.travel.label", nil))];
}

- (void)updateFavorite {
  if (trip_.favorite == nil) {
   Favorite *favorite = [database_ addNewFavoriteWithDistance:trip_.distanceValue purpose:trip_.purpose isBusiness:trip_.isBusinessValue];
    [database_ addTrip:trip_ toFavorite:favorite];
    [database_ saveContext];
  }
  else {
  [database_ deleteFavoriteWithTrip:trip_];
  }
}

@end
