//
//  MainViewController.m
//  Speech Pro
//
//  Created by iO on 2/18/13.
//  Copyright (c) 2013 Oo. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "MainViewController.h"

@interface MainViewController ()

@end

@implementation MainViewController

@synthesize recButton,playButton,playSoundButton,soundPicker;

- (void)viewDidLoad{
    [super viewDidLoad];
    
    NSURL*temporaryRecFile=[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"VoiceFile"]];
    
    recorder=[[AVAudioRecorder alloc]initWithURL:temporaryRecFile settings:nil error:nil];
    
    [recorder prepareToRecord];
    
    AVAudioSession*audioSession=[AVAudioSession sharedInstance];
    
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    [audioSession setActive:YES error:nil];
    
    if([self isHeadsetPluggedIn]==NO){
        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride),&audioRouteOverride);
    }
    
    [self performSelector:@selector(setupdict)];
    
    path=[[NSBundle mainBundle]pathForResource:@"I" ofType:@"mp3"];//to prevent initial launch error
    
    [playSoundButton setTitle:@"\"I\"" forState:UIControlStateNormal];
    
}

-(void)setupdict{
    NSString*resourcePath=[[NSBundle mainBundle]resourcePath];
    NSString*documentsPath=[resourcePath stringByAppendingPathComponent:@"English"];
    
    soundsName=[[NSFileManager defaultManager]contentsOfDirectoryAtPath:documentsPath error:nil];
    sounds=[NSMutableArray new];
    
    for(int i=0; i<soundsName.count; i++) {
        NSString*dPath=[documentsPath stringByAppendingPathComponent:[soundsName objectAtIndex:i]];
        
        [sounds addObject:[[NSFileManager defaultManager]contentsOfDirectoryAtPath:dPath error:nil]];
        
        for (int a=0; a<[[sounds objectAtIndex:i] count]; a++) {
            
            NSString*correctedName=[[[sounds objectAtIndex:i] objectAtIndex:a] stringByReplacingOccurrencesOfString:@".mp3" withString:@""];
            [[sounds objectAtIndex:i] replaceObjectAtIndex:a withObject:correctedName];
        }
    }
}

- (BOOL)isHeadsetPluggedIn {
    UInt32 routeSize = sizeof (CFStringRef);
    CFStringRef route;
    
    OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,&routeSize,&route);
    
    /* Known values of route:
     * "Headset"
     * "Headphone"
     * "Speaker"
     * "SpeakerAndMicrophone"
     * "HeadphonesAndMicrophone"
     * "HeadsetInOut"
     * "ReceiverAndMicrophone"
     * "Lineout"
     */
    
    if (!error && (route != NULL)) {
        NSString* routeStr = (__bridge NSString*)route;
        NSRange headphoneRange = [routeStr rangeOfString : @"Head"];
        if (headphoneRange.location != NSNotFound) return YES;
    }
    return NO;
}

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

-(IBAction)stopRecord:(id)sender{
    [recordingTimer invalidate];
    recordingTimer=nil;
    
    if (recorder.recording)
        [recorder stop];
    
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc]initWithContentsOfURL:recorder.url error:nil];
        [player play];
    }
}

- (IBAction)playSound:(id)sender {
    if([self isHeadsetPluggedIn]==NO){
        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride),&audioRouteOverride);
    }
    
    player=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
    [player play];
}

-(void)recording{
    if (!recorder.recording){
        [recorder record];
    }
}

- (IBAction)record:(id)sender {
    
    if(recorder.recording)
        [recorder stop];
    
    if(player.playing)
        [player stop];
	
    recordingTimer=[NSTimer scheduledTimerWithTimeInterval:1./60.f target:self selector:@selector(recording) userInfo:nil repeats:YES];
}

- (IBAction)play:(id)sender {
    if([self isHeadsetPluggedIn]==NO){
        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride),&audioRouteOverride);
    }
    
    if(recorder.recording)
        [recorder stop];
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc]initWithContentsOfURL:recorder.url error:nil];
        [player play];
    }
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    @try {
        if(component==0) {
            return soundsName.count;
        }
        if(component==1){
            return [[sounds objectAtIndex:[pickerView selectedRowInComponent:0]]count];
        }
    }
    @catch (NSException *exception) {
        //NSLog(@"the exception %@",exception);
    }
    
    return 0;
}

-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    @try {
        if(component==0) {
            return [soundsName objectAtIndex:row];
        }
        if(component==1){
            return [[sounds objectAtIndex:[pickerView selectedRowInComponent:0]]objectAtIndex:row];
        }
    }
    @catch (NSException *exception) {
        //NSLog(@"the exception %@",exception);
    }
    
    return nil;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    [pickerView reloadAllComponents];
    
    @try {
        NSString*soundPath=[@"/English" stringByAppendingPathComponent:[soundsName objectAtIndex:[pickerView selectedRowInComponent:0]]];
        
        NSString*filePath=[[sounds objectAtIndex:[pickerView selectedRowInComponent:0]] objectAtIndex:[pickerView selectedRowInComponent:1]];
        
        NSString*totalPath=[soundPath stringByAppendingPathComponent:filePath];
        
        path=[[NSBundle mainBundle]pathForResource:totalPath ofType:@"mp3"];
        
        NSString*display=[NSString stringWithFormat:@"\"%@\"",filePath];
        
        [playSoundButton setTitle:display forState:UIControlStateNormal];
        
        player=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
        [player play];
        
    }
    @catch (NSException *exception) {
        //NSLog(@"the exception %@",exception);
    }
}

#pragma mark - Flipside View Controller

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.flipsidePopoverController dismissPopoverAnimated:YES];
    }
}

- (IBAction)showInfo:(id)sender
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil];
        controller.delegate = self;
        controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentViewController:controller animated:YES completion:nil];
    } else {
        if (!self.flipsidePopoverController) {
            FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil];
            controller.delegate = self;
            
            self.flipsidePopoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
        }
        if ([self.flipsidePopoverController isPopoverVisible]) {
            [self.flipsidePopoverController dismissPopoverAnimated:YES];
        } else {
            [self.flipsidePopoverController presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
    }
}

@end
