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

#import "AddTripViewController.h"
#import "Database+Trips.h"
#import "Constants.h"
#import "CustomSegmentControl.h"
#import "Database+Odometer.h"
#import "FavoritesViewController.h"
#import "Trip.h"
#import "Favorite.h"

#define kDateCellRow       0
#define kDistanceCellRow   1
#define kOdometerCellRow   2
#define kPurposeCellRow    3

#define kSectionFavorite   1

@interface AddTripViewController (Private)

- (void)cancelButtonPressed;
- (void)showPickerOnView:(UIView *)view;
- (void)hidePickerFromView:(UIView *)view;
- (void)saveButtonPressed;
- (void)segmentValueChanged;

@end
@implementation AddTripViewController

@synthesize odometerCell = odometerCell_;
@synthesize distanceCell = distanceCell_;
@synthesize dateCell = dateCell_;
@synthesize headerView = headerView_;
@synthesize odometerLabel = odometerLabel_;
@synthesize distanceLabel = distancelLabel_;
@synthesize dateLabel = dateLabel_;
@synthesize pickDateLabel = pickDateLabel_;
@synthesize odometerField = odometerField_;
@synthesize distanceField = distanceField_;
@synthesize segmentedControl = segmentedControl_;
@synthesize pickerView = pickerView_;
@synthesize datePicker = datePicker_;
@synthesize database = database_;
@synthesize isBusiness = isBusiness_;
@synthesize purposeField = purposeField_;
@synthesize purposeLabel = purposeLabel_;
@synthesize purposeCell = purposeCell_;
@synthesize pickerDoneButton = pickerDoneButton_;
@synthesize selectedFavorite = selectedFavorite_;

- (id)init 
{
    self = [super initWithNibName:@"AddTripViewController" 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];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self.navigationController.navigationBar setTintColor:[UIColor darkGrayColor]];
  [self.tableView setTableHeaderView:headerView_];
  NSArray *segments = [NSArray arrayWithObjects:NSLocalizedString(@"trip.view.segment.business.title", nil), NSLocalizedString(@"trip.view.segment.private.title", nil), nil];
  segmentedControl_ = [[CustomSegmentedControl alloc] initWithItems:segments offColor:[UIColor grayColor] onColor:[UIColor orangeColor]];
  [segmentedControl_ setFrame:CGRectMake(57, 25, 207, 30)];
  [headerView_ addSubview:segmentedControl_];
  [self segmentValueChanged];
  UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed)];
  [cancelButton setTintColor:[UIColor orangeColor]];
  [self.navigationItem setLeftBarButtonItem:cancelButton];
  [self setTitle:NSLocalizedString(@"add.trip.view.title", nil)];
  
  UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveButtonPressed)];
  [saveButton setTintColor:[UIColor orangeColor]];
  [self.navigationItem setRightBarButtonItem:saveButton];
  
  [segmentedControl_ addTarget:self
                       action:@selector(segmentValueChanged)
             forControlEvents:UIControlEventValueChanged];
  [self displayDate:self];
  [pickerDoneButton_ setTitle:NSLocalizedString(@"button.title.done", nil)];
}

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

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  if (section == kSectionFavorite) {
    return 1;
  }
  return 4;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  }
  if (indexPath.section == kSectionFavorite) {
    [cell.textLabel setText:NSLocalizedString(@"favorites.view.title", nil)];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell.textLabel setFont:[UIFont systemFontOfSize:17.0]];
    [cell.textLabel setTextColor:[UIColor darkGrayColor]];
    return cell;
  }
  switch (indexPath.row) {
    case kDateCellRow:
    {
      [dateLabel_ setText:NSLocalizedString(@"add.trip.view.date.cell.title", nil)];
      return dateCell_;
    }
    case kOdometerCellRow: 
    {
      [odometerLabel_ setText:NSLocalizedString(@"add.trip.view.odometer.cell.title", nil)];
      [odometerField_ setText:[NSString stringWithFormat:@"%.1f", [database_ newestOdometerState]+[distanceField_.text doubleValue]]];
      return odometerCell_;
    }
    case kDistanceCellRow:
    {
      [distancelLabel_ setText:NSLocalizedString(@"add.trip.view.distance.cell.title", nil)];
      return distanceCell_;
    }
    case kPurposeCellRow:
    {
      [purposeLabel_ setText:NSLocalizedString(@"add.trip.view.purpose.title", nil)];
      return purposeCell_;
    }
    default:
      break;
  }
  
  return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:NO];
  if (indexPath.row != kDateCellRow) {
    [self hidePickerFromView:self.view];
  }
  if (indexPath.section == kSectionFavorite) {
    FavoritesViewController *controller = [[FavoritesViewController alloc] init];
    [controller setDatabase:database_];
    [controller setSelectFavoriteMode:YES];
    [controller setDelegate:self];
    [self.navigationController pushViewController:controller animated:YES];
    return;
  }
  switch (indexPath.row) {
    case kDateCellRow:
    {
      [odometerField_ resignFirstResponder];
      [distanceField_ resignFirstResponder];
      [purposeField_ resignFirstResponder];
      [self showPickerOnView:self.view];
      break;
    }
    case kDistanceCellRow:
    {
      [odometerField_ resignFirstResponder];
      [distanceField_ becomeFirstResponder];
      break;
    }
    case kOdometerCellRow:
    {
      [distanceField_ resignFirstResponder];
      [odometerField_ setText:[NSString stringWithFormat:@"%.1f", [database_ newestOdometerState]+[distanceField_.text doubleValue]]];
      [odometerField_ becomeFirstResponder];
      break;
    }
    case kPurposeCellRow:
    {
      [odometerField_ resignFirstResponder];
      [purposeField_ becomeFirstResponder];
      break;
    }
      
    default:
      break;
  }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
  [self hidePickerFromView:self.view];
  if (textField == odometerField_) {
    [odometerField_ setText:[NSString stringWithFormat:@"%.1f", [database_ newestOdometerState]+[distanceField_.text doubleValue]]];
  }
  return YES;
}

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

- (void)cancelButtonPressed {
  [self dismissModalViewControllerAnimated:TRUE];
}

- (void)saveButtonPressed {
  [TestFlight passCheckpoint:@"save trip manually"];
  if ([odometerField_.text length] > 0 && [distanceField_.text length] > 0) {
    double dist = [distanceField_.text doubleValue];
    double odom = [odometerField_.text doubleValue];
    if (selectedFavorite_.purpose == purposeField_.text && selectedFavorite_.distanceValue == dist) {
      [TestFlight passCheckpoint:@"add new trip manually with favorite"];
      [database_ addTripWithDistance:dist endState:odom isBusiness:selectedFavorite_.isBusinessValue date:datePicker_.date purpose:purposeField_.text favorite:selectedFavorite_];
    }
    else {
      [database_ addTripWithDistance:dist endState:odom isBusiness:isBusiness_ date:datePicker_.date purpose:purposeField_.text];
    }
    [self dismissModalViewControllerAnimated:TRUE];
  } else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                    message:NSLocalizedString(@"add.trip.view.alert.fields" , nil) 
                                                   delegate:nil 
                                          cancelButtonTitle:NSLocalizedString(@"button.title.OK", nil) 
                                          otherButtonTitles:nil, nil];
    [alert show];
  }
}

- (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];
}

- (void)segmentValueChanged {
  if ([segmentedControl_ selectedSegmentIndex] == 0) {
    [self setIsBusiness:TRUE];
  }
  else {
    [self setIsBusiness:FALSE];
  }
}

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

- (IBAction)pickerDoneButtonPressed:(id)sender {
  [self hidePickerFromView:self.view];
}

- (void)updateWithFavorite:(Favorite *)favoriteTrip {
  
  [purposeField_ setText:favoriteTrip.purpose];
  [distanceField_ setText:[NSString stringWithFormat:@"%.1f", favoriteTrip.distanceValue]];
  [odometerField_ setText:[NSString stringWithFormat:@"%.1f", [database_ newestOdometerState] + favoriteTrip.distanceValue]];
  [segmentedControl_ setSelectedSegmentIndex:(favoriteTrip.isBusinessValue ? 0 : 1)];
  //TODO Triin: check why segment doesnt want to changes
  MSLog(@"selected %d", segmentedControl_.selectedSegmentIndex);
  [self segmentValueChanged];
  [self setSelectedFavorite:favoriteTrip];
}

@end
