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

#import "ExportSettingsViewController.h"
#import "CHCSVWriter.h"
#import "Export.h"
#import "Period.h"
#import "SelectPeriodViewController.h"
#import "TwoLabelCell.h"
#import "TextFieldCell.h"
#import "Database+User.h"
#import "User.h"
#import "Constants.h"
#import "UITableViewCell+Extensions.h"
#import "NSDate+Extensions.h"
#import "MBProgressHUD.h"

#define kSectionEmail     0
#define kSectionDate      1
#define kSectionCategory  2

#define kRowBusiness      0
#define kRowPrivate       1
#define kRowAll           2

@interface ExportSettingsViewController ()

- (void)sendButtonPressed;
- (void)showPickerOnView:(UIView *)view;
- (void)hidePickerFromView:(UIView *)view;
- (void)sendEmail;

@end

@implementation ExportSettingsViewController

@synthesize pickerView = pickerView_;
@synthesize datePicker = datePicker_;
@synthesize doneButton = doneButton_;
@synthesize database = database_;
@synthesize exportPeriod = exportPeriod_;
@synthesize beginDateCell = beginDateCell_;
@synthesize endDateCell = endDateCell_;
@synthesize emailCell = emailCell_;
@synthesize selectedDateCell = selectedDateCell_;
@synthesize hud = hud_;

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

- (void)viewDidLoad
{
  [super viewDidLoad]; 
  if (exportPeriod_ == nil) {
    exportPeriod_ = [[Period alloc] initWithPeriod:previousMonth];
  }
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self.navigationItem setTitle:NSLocalizedString(@"export.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;
  
  UIBarButtonItem *sendButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"export.view.send.button.title", nil) 
                                                                 style:UIBarButtonItemStylePlain 
                                                                target:self 
                                                                action:@selector(sendButtonPressed)];
  [sendButton setTintColor:[UIColor orangeColor]];
  [self.navigationItem setRightBarButtonItem:sendButton];
  
  [doneButton_ setTitle:NSLocalizedString(@"button.title.done", nil)];
}

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [self hidePickerFromView:self.navigationController.view];
  
}

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

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

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  //TODO triin: implement exporting only private or only business trips
  return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  if (section == kSectionEmail) {
    return 1;
  }
  else if (section == kSectionDate) {
    return 3;
  }
  else if (section == kSectionCategory) {
    return 3;
  }  
  return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  if (section == kSectionDate) {
    return NSLocalizedString(@"export.view.date.section.title", nil);
  }
  else if (section == kSectionCategory) {
    return NSLocalizedString(@"export.view.category.section.title", nil);
  }
  else {
    return nil;
  }
}

- (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];
  }
  [cell.textLabel setFont:[UIFont systemFontOfSize:17.0]];
  [cell.textLabel setTextColor:[UIColor darkGrayColor]];
  [cell setBackgroundColor:[UIColor clearColor]];
  [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
  User *currentUser = [database_ currentUser];
  
  switch (indexPath.section) {
    case kSectionEmail:      
      [self setEmailCell:(TextFieldCell *)[UITableViewCell loadCellFromXib:@"TextFieldCell"]];
      [emailCell_.titleLabel setText:NSLocalizedString(@"export.view.email.section.title", nil)];
      [emailCell_.textField setText:currentUser.email];
      [emailCell_.textField setKeyboardType:UIKeyboardTypeEmailAddress];
      [emailCell_.textField setReturnKeyType:UIReturnKeyDone];
      [emailCell_.textField setDelegate:self];
      return emailCell_;
      break;
    case kSectionDate:
      if (indexPath.row == 0) {
        [self setBeginDateCell:(TwoLabelCell *)[UITableViewCell loadCellFromXib:@"TwoLabelCell"]];
        [beginDateCell_ setValuesForTitleLabel:NSLocalizedString(@"export.view.begin.date.row", nil) 
                                 andValueLabel:[exportPeriod_.beginningDate stringFromDate]];
        return beginDateCell_;
      }
      else if (indexPath.row == 1) {
        [self setEndDateCell:(TwoLabelCell *)[UITableViewCell loadCellFromXib:@"TwoLabelCell"]];
        [endDateCell_ setValuesForTitleLabel:NSLocalizedString(@"export.view.end.date.row", nil) 
                               andValueLabel:[exportPeriod_.endDate stringFromDate]];
        return endDateCell_;
      }
      else if (indexPath.row == 2) {
        [cell.textLabel setText:NSLocalizedString(@"export.view.select.period.row", nil)];
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        return cell;
      }
      break;
    case kSectionCategory:
      if (indexPath.row == kRowBusiness) {
        [cell.textLabel setText:NSLocalizedString(@"export.view.business.category.row", nil)];
        return cell;
      }
      else if (indexPath.row == kRowPrivate) {
        [cell.textLabel setText:NSLocalizedString(@"export.view.private.category.row", nil)];
        return cell;
      }
      else if (indexPath.row == kRowAll) {
        [cell.textLabel setText:NSLocalizedString(@"export.view.both.category.row", nil)];
        return cell;
      }
    default:
      break;
  }
  
  [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
  return cell;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
  if (indexPath.section != 1) {
    [self hidePickerFromView:self.navigationController.view];
  }
  switch (indexPath.section) {
  
    case kSectionEmail:
      [emailCell_.textField becomeFirstResponder];
    case kSectionDate:
      if (indexPath.row == 0) {
        [self setSelectedDateCell:beginDateCell_];
        [self showPickerOnView:self.navigationController.view];
      }
      else if (indexPath.row == 1) {
        [self setSelectedDateCell:endDateCell_];
        [self showPickerOnView:self.navigationController.view];
      }
      else if (indexPath.row == 2) {
        SelectPeriodViewController *controller = [[SelectPeriodViewController alloc] init];
        [controller setSelectedPeriod:exportPeriod_];
        [controller setDelegate:self];
        [self.navigationController pushViewController:controller animated:YES];
      }
      break;
      
    default:
      break;
  }
  
  // Navigation logic may go here. Create and push another view controller.
  /*
   <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
   // ...
   // Pass the selected object to the new view controller.
   [self.navigationController pushViewController:detailViewController animated:YES];
   */
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  User *user = [database_ currentUser];
  if (![textField.text isEqualToString:user.email]) {
    [user setEmail:textField.text];
    [database_ saveContext];
  }
  [textField resignFirstResponder];
  return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
  [self hidePickerFromView:self.navigationController.view];
  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)doneButtonPressed:(id)sender {
  [self hidePickerFromView:self.navigationController.view];
}

- (void)updatePeriodTo:(Period *)newPeriod {
  [self setExportPeriod:newPeriod];
  [self.tableView reloadData];
}

- (IBAction)datePickerValueChanged:(id)sender {
  [selectedDateCell_ updateValue:[datePicker_.date stringFromDate]];
  [self.exportPeriod setPeriodType:custom];
  if (selectedDateCell_ == beginDateCell_) {
    exportPeriod_.beginningDate = datePicker_.date;
  }
  else {
    exportPeriod_.endDate = datePicker_.date;
  }
}

- (void)sendButtonPressed {
  UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"export.view.action.sheet.title", nil) 
                                                           delegate:self 
                                                  cancelButtonTitle:NSLocalizedString(@"button.title.cancel", nil) 
                                             destructiveButtonTitle:nil 
                                                  otherButtonTitles:NSLocalizedString(@"button.title.send", nil), nil];
  [actionSheet showFromTabBar:self.tabBarController.tabBar];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (buttonIndex == 0) {
    if (exportPeriod_ != nil && [[database_ currentUser].email length] > 0) {
      [self sendEmail];
    }
    else {
      NSString *message;
      if (exportPeriod_ == nil) {
        message = NSLocalizedString(@"export.view.alert.missing.period.text", nil);
      }
      else {
        message = NSLocalizedString(@"export.view.alert.missing.email.text", nil);
      }
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"button.title.OK", nil) otherButtonTitles:nil, nil];
      [alert show];
    }
  }
}

- (void)emailSent {  
  
  hud_.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"check.png"]];
  [hud_ setMode:MBProgressHUDModeCustomView];
  [hud_ setLabelText:NSLocalizedString(@"export.view.confirm.hud.text", nil)];
  
  [hud_ hide:YES afterDelay:2];
}

- (void)emailSendFail {
  [hud_ hide:YES];
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"export.view.email.fail.alert.title", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"button.title.no", nil) otherButtonTitles:NSLocalizedString(@"button.title.try.again", nil), nil];
  [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (buttonIndex == 1) {
    [self sendEmail];
  }
}

- (void)sendEmail {
  [TestFlight passCheckpoint:@"send email"];
  Export *export = [[Export alloc] initFrom:exportPeriod_.beginningDate to:exportPeriod_.endDate];
  [export setDatabase:database_];
  [export setDelegate:self];
  [export exportData];
  hud_ = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
  [self.navigationController.view addSubview:hud_];
  [hud_ show:YES];
}

@end
