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

#import "SettingsViewController.h"
#import "Database+Settings.h"
#import "Constants.h"
#import "Setting.h"
#import "UserRegistrationViewController.h"
#import "Database+Trips.h"
#import "Database+User.h"

#define kSectionNavMap        0
#define kSectionUser          1

#define kRowGPS               0
#define kRowMap               1

#define kTagTrips             0
#define kTagUser              1

@interface SettingsViewController ()

- (void)switchToggled:(UISwitch *)aSwitch;
- (void)showAlertForDeletingTrips:(BOOL)trips;

@end

@implementation SettingsViewController

@synthesize database = database_;

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

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

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self.navigationItem setTitle:NSLocalizedString(@"settings.view.title", nil)];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  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 == kSectionNavMap) {    
    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
    [mySwitch setTag:indexPath.row];
    [cell setAccessoryView:mySwitch];
    [mySwitch setOnTintColor:[UIColor orangeColor]];
    [mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents: UIControlEventValueChanged];
    Setting *setting;
    if (indexPath.row == kRowGPS) {
      [cell.textLabel setText:NSLocalizedString(@"settings.view.gps.row.title", nil)];
      setting = [database_ findOrCreateSettingWithTitle:kSettingGPS];
    }
    else if (indexPath.row == kRowMap) {
      [cell.textLabel setText:NSLocalizedString(@"settings.view.map.row.title", nil)];
      setting = [database_ findOrCreateSettingWithTitle:kSettingShowMap];
    }
    [mySwitch setOn:setting.valueValue];
    [cell setSelectionStyle:UITableViewCellEditingStyleNone];
  }
  else if (indexPath.section == kSectionUser) {
    if (indexPath.row == 0) {
      [cell.textLabel setText:NSLocalizedString(@"settings.view.user.row.title", nil)];
    }
    else if (indexPath.row == 1) {
      [cell.textLabel setText:NSLocalizedString(@"settings.view.delete.info.title", nil)];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
  }  
  [cell.textLabel setFont:[UIFont systemFontOfSize:17.0]];
  [cell.textLabel setTextColor:[UIColor darkGrayColor]];
  [cell setBackgroundColor:[UIColor clearColor]];
  return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
  if (indexPath.section == kSectionUser) {
    if (indexPath.row == 0) {
      UserRegistrationViewController *controller = [[UserRegistrationViewController alloc] init];
      [controller setDatabase:database_];
      [self.navigationController pushViewController:controller animated:TRUE];
    }    
    else if (indexPath.row == 1) {
      UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:NSLocalizedString(@"button.title.cancel", nil) otherButtonTitles:NSLocalizedString(@"settings.view.delete.trips.title", nil), NSLocalizedString(@"settings.view.delete.user.title", nil), nil];
      [actionSheet showFromTabBar:self.tabBarController.tabBar];
    }
  }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  MSLog(@"action sheet button index %d", buttonIndex);
  if (buttonIndex == 1) {
    [self showAlertForDeletingTrips:YES];
  } else if (buttonIndex == 2) {
    [self showAlertForDeletingTrips:NO];
  }
}

- (void)switchToggled:(UISwitch *)aSwitch {
  [TestFlight passCheckpoint:@"change map and GPS settings"];
  if ([aSwitch isOn]) {
    [aSwitch setOn:YES animated:YES];
    switch (aSwitch.tag) {
      case kRowGPS:
        [database_ updateSetting:[database_ findOrCreateSettingWithTitle:kSettingGPS] withValue:YES];
        break;
      case kRowMap:
        [database_ updateSetting:[database_ findOrCreateSettingWithTitle:kSettingShowMap] withValue:YES];
        break;
      default:
        break;
    }
  }
  else {
    [aSwitch setOn:NO animated:YES];
    switch (aSwitch.tag) {
      case kRowGPS:
        [database_ updateSetting:[database_ findOrCreateSettingWithTitle:kSettingGPS] withValue:NO];
        break;
      case kRowMap:
        [TestFlight passCheckpoint:@"dont show user location on map"];
        [database_ updateSetting:[database_ findOrCreateSettingWithTitle:kSettingShowMap] withValue:NO];
        break;
      default:
        break;
    }
  }
}

- (void)showAlertForDeletingTrips:(BOOL)trips {
  UIAlertView *alert;
  NSString *message;
  int alertTag;
  if (trips) {
    message = NSLocalizedString(@"settings.view.warning.trips.title", nil);
    alertTag = kTagTrips;   
  }
  else {
    message = NSLocalizedString(@"settings.view.warning.user.title", nil);
    alertTag = kTagUser;
  }
  alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:NSLocalizedString(@"button.title.cancel", nil) otherButtonTitles:NSLocalizedString(@"button.title.OK", nil), nil];
  alert.tag = alertTag;
  [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  MSLog(@"buttonindex %d, alert tag %d", buttonIndex, alertView.tag);
  if (buttonIndex == 1) {
    if (alertView.tag == kTagUser) {
      [TestFlight passCheckpoint:@"delete user"];
      [database_ deleteUser];
    }
    else if (alertView.tag == kTagTrips) {
      [TestFlight passCheckpoint:@"delete all trips"];
      [database_ deleteAllTrips];
    }
  }
  
}

@end
