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

#import "UserRegistrationViewController.h"
#import "Constants.h"
#import "UIView+Extensions.h"
#import "Database+User.h"
#import "Database+Odometer.h"
#import "UITableViewCell+Extensions.h"
#import "TextFieldCell.h"
#import "User.h"

#define kNameRow            0
#define kEmailRow           1
#define kCarNumberRow       2
#define kOdometerStateRow   3
#define kCompanyRow         4
#define kBusinessCodeRow    5


@interface UserRegistrationViewController ()

- (void)doneButtonPressed;
@end

@implementation UserRegistrationViewController

@synthesize nameField = nameField_;
@synthesize companyField = companyField_;
@synthesize carNumberField = carNumberField_;
@synthesize businessCodeField = businessCodeField_;
@synthesize odometerField = odometerField_;
@synthesize odometerLabel = odometerLabel_;
@synthesize emailField = emailField_;
@synthesize database = database_;
@synthesize currentUser_ = currentUser_;

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

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

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self.navigationController.navigationBar setTintColor:[UIColor darkGrayColor]];
  [self.navigationItem setTitle:NSLocalizedString(@"user.registration.view.title", nil)];
  UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"user.registration.view.done.button.title", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed)];
  [doneButton setTintColor:[UIColor orangeColor]];
  [self.navigationItem setRightBarButtonItem:doneButton];
  MSLog(@"currentUser %@", [database_ currentUser]);
  [self setCurrentUser_:[database_ currentUser]];
}

- (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 - Table view data source

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"TextFieldCell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  
  if (cell == nil) {
    cell = [UITableViewCell loadCellFromXib:@"TextFieldCell"];
  }

  [[(TextFieldCell *)cell textField] setDelegate:self];
  
  switch (indexPath.row) {
    case kNameRow:
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"user.registration.view.name.cell", nil)];
      [self setNameField:[(TextFieldCell *)cell textField]];
      [[(TextFieldCell *)cell textField] setAutocapitalizationType:UITextAutocapitalizationTypeWords];
      [[(TextFieldCell *)cell textField] setText:currentUser_.name];
      break;
    case kEmailRow:
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"user.registration.view.email.cell", nil)];
      [self setEmailField:[(TextFieldCell *)cell textField]];
      [[(TextFieldCell *)cell textField] setKeyboardType:UIKeyboardTypeEmailAddress];
      [[(TextFieldCell *)cell textField] setText:currentUser_.email];
      break;
    case kCompanyRow:
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"user.registration.view.company.name.cell", nil)];
      [[(TextFieldCell *)cell textField] setAutocapitalizationType:UITextAutocapitalizationTypeWords];
      [self setCompanyField:[(TextFieldCell *)cell textField]];
      [[(TextFieldCell *)cell textField] setText:currentUser_.company];
      break;
    case kCarNumberRow:
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"user.registration.view.car.number.cell", nil)];
      [[(TextFieldCell *)cell textField] setAutocapitalizationType:UITextAutocapitalizationTypeAllCharacters];
      [[(TextFieldCell *)cell textField] setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
      [self setCarNumberField:[(TextFieldCell *)cell textField]];
      [[(TextFieldCell *)cell textField] setText:currentUser_.carNumber];
      break;
    case kBusinessCodeRow:
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"user.registration.view.business.registry.code.cell", nil)];
      [[(TextFieldCell *)cell textField] setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
      [self setBusinessCodeField:[(TextFieldCell *)cell textField]];
      [[(TextFieldCell *)cell textField] setReturnKeyType:UIReturnKeyDone];
      [[(TextFieldCell *)cell textField] setText:currentUser_.businessRegisterCode];
      break;
    case kOdometerStateRow:       
      [[(TextFieldCell *)cell titleLabel] setText:NSLocalizedString(@"user.registration.view.odometer.state.cell", nil)];
      [[(TextFieldCell *)cell textField] setText:[NSString stringWithFormat:@"%.1f", [database_ newestOdometerState]]];
      [[(TextFieldCell *)cell textField] setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
      [self setOdometerField:[(TextFieldCell *)cell textField]];
      break;      
    default:
      break;
  }
  
  return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [tableView deselectRowAtIndexPath:indexPath animated:NO];
  switch (indexPath.row) {
    case kNameRow:
      [nameField_ becomeFirstResponder];
      break;
    case kEmailRow:
      [emailField_ becomeFirstResponder];
      break;
    case kCompanyRow:
      [companyField_ becomeFirstResponder];
      break;
    case kCarNumberRow:
      [carNumberField_ becomeFirstResponder];
      break;
    case kBusinessCodeRow:
      [businessCodeField_ becomeFirstResponder];
      break;
    case kOdometerStateRow:
      [odometerField_ becomeFirstResponder];
      break;      
    default:
      break;
  }
}

#pragma mark - Text Field Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  
  if (textField == nameField_) {
    [emailField_ becomeFirstResponder];
  }
  else if (textField == emailField_) {
    [carNumberField_ becomeFirstResponder];
  }
  else if (textField == carNumberField_) {
    [odometerField_ becomeFirstResponder];
  }
  else if (textField == odometerField_) {
    [companyField_ becomeFirstResponder];
  }
  else if (textField == companyField_) {
    [businessCodeField_ becomeFirstResponder];
  }
  else if (textField == businessCodeField_) {
    [businessCodeField_ resignFirstResponder];
    [self doneButtonPressed];
  }
  return YES;
}

- (void)doneButtonPressed {
  if ([odometerField_.text doubleValue] > 0) {
    [database_ findOrCreateUserWithName:nameField_.text email:emailField_.text company:companyField_.text carNumber:carNumberField_.text businessRegisterCode:businessCodeField_.text];
    [database_ findOrAddNewOdodmeterWithState:[odometerField_.text doubleValue] date:[NSDate date]];
    [self dismissModalViewControllerAnimated:YES];
  }
  else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                    message:NSLocalizedString(@"user.registration.view.odometer.missing.alert.text", nil) 
                                                   delegate:nil 
                                          cancelButtonTitle:@"OK" 
                                          otherButtonTitles:nil, nil];
    [alert show];
  }  
}

@end
