/*
iPhly: Radio Control on the iPhone

Copyright (C) 2010-2011 Ari Krupnik & Associates

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License V2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#import "ModelNameViewController.h"
#import "ModelConfigController.h"
#import "ChannelConfigViewController.h"
#import "ModelProcessor.h"
#import "ModelProcessorChannel.h"
#import "ModelListViewController.h"
#import "TiltAndSwipeViewController.h"
#import "util_m.h"

enum sections {
	NAME_SECTION,
	ACCELEROMETER_SECTION,
	CHANNELS_SECTION,
	REORDER_CHANNELS_SECTION,
    TRIMS_SECTION,
	DELETE_SECTION,
	NUM_SECTIONS
};

NSString * const REPLACE_PHOTO = @"Replace Photo";
NSString * const ADD_PHOTO = @"Add Photo";

NSString * const TAKE_PHOTO = @"Take Photo";
NSString * const USE_EXISTING_PHOTO = @"Choose Existing Photo";
NSString * const DELETE_PHOTO = @"Delete Photo";

@implementation ModelConfigController

@synthesize processor;
@synthesize accelerometerSensitivityCell;
@synthesize accelerometerSensitivitySlider;
@synthesize accelerometerSensitivityValueLabel;

- (NSString *) reorderCellTitle {
	return [self isEditing] ? @"Reordering Complete" : @"Reorder Channels";
}

- (ModelConfigController *) initWithProcessor: (ModelProcessor *) p {	
	if ((self = [super initWithNibName:@"ModelConfigController" bundle:nil])) {
		[self setProcessor: p];
		
		modelNameCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: nil];
		[modelNameCell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
		
		modelImageCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
		
		[modelImageCell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
		UIImage *img = [p image];
		
		if (img) {
			[[modelImageCell imageView] setImage: thumbNail(img, [modelImageCell frame].size.height, 1)];
			[[modelImageCell textLabel] setText: REPLACE_PHOTO];
		} else {
			[[modelImageCell textLabel] setText: ADD_PHOTO];
		}
        
        trimsVisibleCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        [[trimsVisibleCell textLabel] setText:@"Trim Buttons Visible"];
        [trimsVisibleCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        UISwitch* s = [[[UISwitch alloc] init] autorelease];
        [s addTarget:self action:@selector(trimsVisibleSwitchFlip:) forControlEvents:UIControlEventValueChanged];
        [trimsVisibleCell setAccessoryView:s];
        
        trimsVibrateCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        [[trimsVibrateCell textLabel] setText:@"Vibrate on Trim"];
        [trimsVibrateCell setSelectionStyle:UITableViewCellSeparatorStyleNone];
        s = [[[UISwitch alloc] init] autorelease];
        [s addTarget:self action:@selector(trimsVibrateSwitchFlip:) forControlEvents:UIControlEventValueChanged];
        [trimsVibrateCell setAccessoryView:s];
        s = nil;

		reorderCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
		[[reorderCell textLabel] setText: [self reorderCellTitle]];
		
		deleteCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: nil];
		[[deleteCell textLabel] setTextAlignment:UITextAlignmentCenter];
		[[deleteCell textLabel] setTextColor:[UIColor redColor]];
		[[deleteCell textLabel] setText: @"Delete Model"];
	}
	return self;
}

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

/*
- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	[accelerometerSensitivitySlider setValue:[processor accelerometerSensitivity]];
	[accelerometerSensitivityValueLabel setText:[NSString stringWithFormat:@"%3.2f", [processor accelerometerSensitivity]]];
	[accelerometerSensitivitySlider addTarget:self action:@selector(accelerometerSensitivityDrag:) forControlEvents:UIControlEventValueChanged];
    
    UISwitch* vis = (UISwitch*)[trimsVisibleCell accessoryView];
    UISwitch* vib = (UISwitch*)[trimsVibrateCell accessoryView];
    [vis setOn:[processor trimsVisible] animated:NO];
    [vib setOn:[processor trimsVibrate] animated:NO];
    [vib setEnabled:[vis isOn]];

	[[modelNameCell textLabel] setText: [processor name]];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	[self setTitle: @"Model Config"];
	[[self tableView] reloadData];
	[[self tableView] setAllowsSelectionDuringEditing:YES];
}


- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	[self setEditing:NO];
	[[reorderCell textLabel] setText: [self reorderCellTitle]];
}

/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (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.
}

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


#pragma mark Table view methods

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


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	switch (section) {
		case NAME_SECTION:
        case TRIMS_SECTION:
			return 2;
		case ACCELEROMETER_SECTION:
		case REORDER_CHANNELS_SECTION:
		case DELETE_SECTION:
			return 1;
		case CHANNELS_SECTION:
			return [processor numChannels];
		default:
			return 0;
	}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	switch(section) {
		case NAME_SECTION:
			return @"Name";
		case ACCELEROMETER_SECTION:
			return @"Accelerometer Response";
		case CHANNELS_SECTION:
			return @"Channels";
		default:
			return nil;
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	switch ([indexPath section]) {
		case NAME_SECTION:
			switch ([indexPath row]) {
				case 0:
					return modelNameCell;
				default:
					return modelImageCell;
			}
		case ACCELEROMETER_SECTION:
			return accelerometerSensitivityCell;
        case TRIMS_SECTION:
            switch ([indexPath row]) {
                case 0:
                    return trimsVisibleCell;
                default:
                    return trimsVibrateCell;
            }
		case CHANNELS_SECTION: {
			static NSString *ChannelCellId = @"ChannelCell";
			UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ChannelCellId];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ChannelCellId] autorelease];
				[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
			}
			ModelProcessorChannel *ch = [processor channelAtIndex: [indexPath row]];
			[[cell textLabel] setText: [NSString stringWithFormat:@"%d: %@", [ch ord]+1, [ch name]]];
			[[cell detailTextLabel] setText: [NSString stringWithFormat:@"%@ trim: %3.2f rate: %3.2f", [ch reversing]?@"rev":@"nor", [ch trim], [ch rate]]];
			return cell;
		}
		case REORDER_CHANNELS_SECTION: {
			[[reorderCell textLabel] setText: [self reorderCellTitle]];
			return reorderCell;
		}
		case DELETE_SECTION:
			return deleteCell;
	}
    // throw "can't get here" exception?
	return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	switch ([indexPath section]) {
		case NAME_SECTION: {
			if ([indexPath row]==0) {
				ModelNameViewController *mnvc = [[ModelNameViewController alloc] initWithProcessor: processor];
				[self.navigationController pushViewController:mnvc animated:YES];
				[mnvc release];
			} else {
				UIActionSheet *imgSrc;
				if ([processor image]) {
					if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
						imgSrc = [[UIActionSheet alloc]
								  initWithTitle:nil
								  delegate:self
								  cancelButtonTitle:@"Cancel"
								  destructiveButtonTitle:nil
								  otherButtonTitles:TAKE_PHOTO, USE_EXISTING_PHOTO, DELETE_PHOTO, nil];
					} else {
						imgSrc = [[UIActionSheet alloc]
								  initWithTitle:nil
								  delegate:self
								  cancelButtonTitle:@"Cancel"
								  destructiveButtonTitle:nil
								  otherButtonTitles:USE_EXISTING_PHOTO, DELETE_PHOTO, nil];
					}
				} else {
					if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
						imgSrc = [[UIActionSheet alloc]
								  initWithTitle:nil
								  delegate:self
								  cancelButtonTitle:@"Cancel"
								  destructiveButtonTitle:nil
								  otherButtonTitles:TAKE_PHOTO, USE_EXISTING_PHOTO, nil];
					} else {
						imgSrc = [[UIActionSheet alloc]
								  initWithTitle:nil
								  delegate:self
								  cancelButtonTitle:@"Cancel"
								  destructiveButtonTitle:nil
								  otherButtonTitles:USE_EXISTING_PHOTO, nil];
					}
				}

				[imgSrc showInView:[self view]];
				[imgSrc release];
			}
			break;
		}
		case ACCELEROMETER_SECTION:
        case TRIMS_SECTION:
			break;
		case CHANNELS_SECTION: {
			ChannelConfigViewController *ccc = [[ChannelConfigViewController alloc]
												//initWithProcessor:processor andChannel: NSSelectorFromString([[processor channelAtIndex:[indexPath row]] name])];
												initWithProcessor:processor andChannel: [processor channelAtIndex:[indexPath row]]];
			[self.navigationController pushViewController:ccc animated: YES];
			[ccc release];
			break;
		}
		case REORDER_CHANNELS_SECTION:
			[self setEditing: ![self isEditing] animated:YES];
			[[reorderCell textLabel] setText: [self reorderCellTitle]];
			break;
		case DELETE_SECTION: {
			// pop up confirm dialog
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Delete Model"
															 message:[NSString stringWithFormat: @"About to delete \"%@\"", [processor name]]
															delegate:self
												   cancelButtonTitle:@"Cancel"
												   otherButtonTitles:@"Delete", nil] autorelease];
			[alert show];
			[(UITableView *)[self view] deselectRowAtIndexPath:indexPath animated: YES];
			break;
		}
	}
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
	if ([fromIndexPath section] == CHANNELS_SECTION) {
		[processor changeOutputOrderForChannel:[fromIndexPath row] to:[toIndexPath row]];
		
		// update channel numbers
		[[self tableView] performSelector:@selector(reloadData) withObject:nil afterDelay:0.02];
	}
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return [indexPath section] == CHANNELS_SECTION;
}

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
	if ([proposedDestinationIndexPath section] == CHANNELS_SECTION) {
		return proposedDestinationIndexPath;
	} else {
		return sourceIndexPath;
	}
}


- (IBAction) accelerometerSensitivityDrag: (UISlider *) target {
	[accelerometerSensitivityValueLabel setText: [NSString stringWithFormat:@"%3.2f", [target value]]];
	[processor setAccelerometerSensitivity:[target value]];
}

- (void) trimsVisibleSwitchFlip: (UISwitch*) s {
    [processor setTrimsVisible:[s isOn]];
    [(UISwitch*)[trimsVibrateCell accessoryView] setEnabled:[s isOn]];
}
- (void) trimsVibrateSwitchFlip: (UISwitch*) s {
    [processor setTrimsVibrate:[s isOn]];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        TiltAndSwipeViewController* old = [[[self navigationController] viewControllers] objectAtIndex:0];
        [[old processor] stopTransmission];
		[processor delete];
        NSArray* controllers = [NSArray arrayWithObject:[[[ModelListViewController alloc] init] autorelease]];
        [[self navigationController] setViewControllers:controllers animated:YES];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	UIImagePickerControllerSourceType imgSrc;
	[modelImageCell setSelected:NO];
	if ([actionSheet buttonTitleAtIndex:buttonIndex]==TAKE_PHOTO) {
		imgSrc = UIImagePickerControllerSourceTypeCamera;
	} else if ([actionSheet buttonTitleAtIndex:buttonIndex]==USE_EXISTING_PHOTO) {
		imgSrc = UIImagePickerControllerSourceTypePhotoLibrary;
	} else if ([actionSheet buttonTitleAtIndex:buttonIndex]==DELETE_PHOTO) {
		[processor setImage:nil];
		[[modelImageCell imageView] setImage:nil];
		[[modelImageCell textLabel] setText:ADD_PHOTO];
		return;
	} else {
		// cancel or bug
		return;
	}
	
	UIImagePickerController *ip = [[UIImagePickerController alloc] init];
	[ip setDelegate:self];
	[ip setAllowsEditing:YES];
	[ip setSourceType: imgSrc];
	[self presentModalViewController:ip animated:YES];
	[ip release];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
	
	[processor setImage:editedImage];
	
	[[modelImageCell imageView] setImage:thumbNail(editedImage, [modelImageCell frame].size.height, 1)];
	[[modelImageCell textLabel] setText:REPLACE_PHOTO];
	[[self tableView] reloadData];
	
	[self dismissModalViewControllerAnimated:YES];
}


- (void)dealloc {
	[processor release];
	[modelNameCell release];
	[modelImageCell release];
	[accelerometerSensitivityCell release];
	[accelerometerSensitivitySlider release];
	[accelerometerSensitivityValueLabel release];
    [trimsVisibleCell release];
    [trimsVibrateCell release];
    [super dealloc];
}


@end

