//
//  voiceRecorderViewController.m
//  melody app
//
//  Created by Odin on 09/03/2017.
//  Copyright © 2017 demain un autre jour. All rights reserved.
//

#import "voiceRecorderViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <CommonCrypto/CommonDigest.h>

@interface voiceRecorderViewController () {
	BOOL recording;
	
	AVAudioRecorder *recorder;
	AVAudioPlayer *player;
	NSString* soundDirectoryPath;
	NSURL *outputFileURL;
	AVAudioSession *session;
	
	BOOL isForSoundManager;
	int currentArticleId;
}
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
@property (weak, nonatomic) IBOutlet UIButton *addToArticleButton;
@property (weak, nonatomic) IBOutlet UIButton *recordActionButton;

@end

@implementation voiceRecorderViewController

- (void)viewDidLoad {
	[super viewDidLoad];
		
	CGRect screen = [[UIScreen mainScreen] bounds];
	self.view.frame = screen;
	[self.recordActionButton setBackgroundImage:[UIImage imageNamed:@"microIconWait"] forState:UIControlStateNormal];
	[self prepareNewRecording];
	
	//var init
	recording = false;
	
	[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(orientationChanged:)
												 name:UIDeviceOrientationDidChangeNotification
											   object:nil];
}

- (void)orientationChanged:(NSNotification *)notification
{
	CGRect screen = [[UIScreen mainScreen] bounds];
	self.view.frame = screen;
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}


- (void)showInView:(UIView *)aView animated:(BOOL)animated valueToEdit:(NSString*) valueEdit articleId:(int) articleId forSoundManager:(BOOL)forSoundManager {
	currentArticleId = articleId;
	soundDirectoryPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/sounds/"];
	
	[self showInView:aView animated:animated valueToEdit:valueEdit forSoundManager:forSoundManager];
}


- (void)showInView:(UIView *)aView animated:(BOOL)animated valueToEdit:(NSString*) valueEdit forSoundManager:(BOOL)forSoundManager {
	isForSoundManager = forSoundManager;
	[aView addSubview:self.view];
	if (animated) {
		[self showAnimate];
	}
}

- (void)showAnimate {
	self.view.transform = CGAffineTransformMakeScale(1.0, 1.0);
	self.view.alpha = 0;
	[UIView animateWithDuration:.25 animations:^{
		self.view.alpha = 1;
		self.view.transform = CGAffineTransformMakeScale(1, 1);
	}];
}

- (IBAction)processRecording:(id)sender {
	if (recording == false) {
		recording = true;
		[self.recordActionButton setBackgroundImage:[UIImage imageNamed:@"microIconRecording"] forState:UIControlStateNormal];
		[self launchRecording];
		//[self recordingTest];
	} else if (recording == true) {
		recording = false;
		[self.recordActionButton setBackgroundImage:[UIImage imageNamed:@"microIconWait"] forState:UIControlStateNormal];
		[self pauseRecording];
	}
}

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

- (void) pauseRecording {
	if (recorder.recording) {
		// Pause recording
		[recorder pause];
	}
}
- (IBAction)addRecording:(id)sender {
	[recorder stop];
	[session setActive:NO error:nil];
	
	NSData* recordData =  [NSData dataWithContentsOfURL:recorder.url];
	
	NSDictionary* userInfo = @{@"soundData": recordData};
	
	if (isForSoundManager == true) {
		[[NSNotificationCenter defaultCenter] postNotificationName:@"addSoundToLibrary" object:self userInfo:userInfo];
	} else {
		[[NSNotificationCenter defaultCenter] postNotificationName:@"addSoundToArticle" object:self userInfo:userInfo];
	}
	
	[self closeThisView];
}

- (void) prepareNewRecording {
	// Set the audio file
	NSArray *pathComponents = [NSArray arrayWithObjects:
							   [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
							   @"MyAudioMemo.m4a",
							   nil];
	NSURL *tmpoutputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
	
	// Setup audio session
	session = [AVAudioSession sharedInstance];
	[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
 
	// Define the recorder setting
	NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
	
	[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
	[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
	[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
	
	// Initiate and prepare the recorder
	recorder = [[AVAudioRecorder alloc] initWithURL:tmpoutputFileURL settings:recordSetting error:NULL];
	recorder.delegate = self;
	recorder.meteringEnabled = YES;
	[recorder prepareToRecord];
	
	session = [AVAudioSession sharedInstance];
	[session setActive:YES error:nil];
}

- (IBAction)closeView:(id)sender {
	[self closeThisView];
	
}

- (void) closeThisView {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.25];
	[UIView  setAnimationDelegate:self];
	[self.view setAlpha:0.00];
	[UIView commitAnimations];
}

- (NSString *)NSDataToMD5String:(NSData*) data {
	unsigned char *cstr = (unsigned char *)[data bytes];
	unsigned char result[32];
	CC_MD5(cstr, strlen(cstr), result);
	
	return [NSString stringWithFormat:
			@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1], result[2], result[3],
			result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11],
			result[12], result[13], result[14], result[15],
			result[16], result[17], result[18], result[19],
			result[20], result[21], result[22], result[23],
			result[24], result[25], result[26], result[27],
			result[28], result[29], result[30], result[31],
			result[32]
			];
}

@end
