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

#import "soundManagerViewController.h"
#import "VoiceRecorderViewController.h"
#import "showImageViewViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "sql/ZIMSqlSdk.h"
#import "sql/ZIMOrmSdk.h"
#import "sql/ZIMDbSdk.h"
#import "DBmanager.h"

@interface soundManagerViewController () <UITableViewDelegate, UITableViewDataSource> {
	NSString* soundDirectoryPath;
	NSArray* soundDirectoryContent;
	BOOL addSoundToArticle;
	int articleId;
}
@property (weak, nonatomic) IBOutlet UITableView *soundDirectoryTableView;
@property (weak, nonatomic) IBOutlet UIButton *addSondButton;

@end

@implementation soundManagerViewController


- (void)viewDidLoad {
	[super viewDidLoad];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAddSoundToLibraryNotification:) name:@"addSoundToLibrary" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEditEndedNotification:) name:@"PhotoTerminated" object:nil];
	self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"baseData.sql"];
	
	CGRect screen = [[UIScreen mainScreen] bounds];
	self.view.frame = screen;
	
	[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(orientationChanged:)
												 name:UIDeviceOrientationDidChangeNotification
											   object:nil];
	[self updateSoundDirectoryContent];
	self.soundDirectoryTableView.delegate = self;
	self.soundDirectoryTableView.dataSource = self;
	self.soundDirectoryTableView.allowsMultipleSelectionDuringEditing = NO;
}

-(void) updateSoundDirectoryContent {
	if (![[NSFileManager defaultManager] fileExistsAtPath:soundDirectoryPath]) {
		[[NSFileManager defaultManager] createDirectoryAtPath:soundDirectoryPath withIntermediateDirectories:YES attributes:nil error:nil];
	}

	soundDirectoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:soundDirectoryPath error: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 articleId:(int) artId {
	articleId = artId;
	[self showInView:aView animated:animated toAddToArticle:true];
	
}

- (void)showInView:(UIView *)aView animated:(BOOL)animated  toAddToArticle:(BOOL)toAddToArticle {
	soundDirectoryPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/sounds/"]];
	addSoundToArticle = toAddToArticle;
	
	[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)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];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"PhotoTerminated" object:self];
}


- (void)addSoundToLibrary: (NSData*)soundData {
	NSString *pathDataSounds = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/sounds"];
	if (![[NSFileManager defaultManager] fileExistsAtPath:pathDataSounds]) {
		[[NSFileManager defaultManager] createDirectoryAtPath:pathDataSounds withIntermediateDirectories:NO attributes:nil error:nil];
	}
	
	NSString* extension = @"mp4";
	NSString* fileName = [[self NSDataToMD5String:soundData] stringByAppendingString:[NSString stringWithFormat:@".%@", extension]];
	NSString* filePath = [pathDataSounds stringByAppendingString: [NSString stringWithFormat:@"/%@", fileName]];
	
	//SAVING sound TO DIRECTORY
	[self saveSound:soundData soundName:fileName soundPath:filePath];
	
	[self.soundDirectoryTableView reloadData];
	filePopUp = [showImageViewViewController alloc];
	filePopUp.mediaType = @"sound";
	[filePopUp showInView:self.view	animated:YES valueToEdit:fileName isForLibrary:true];
}


- (void)saveSound:(NSData*)soundData soundName:(NSString*)soundName soundPath:(NSString*)soundPath {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *query;
	ZIMSqlInsertStatement *myInsertQuery = [[ZIMSqlInsertStatement alloc] init];
	[myInsertQuery into:@"sound"];
	[myInsertQuery column:@"soundName" value:soundName];
	[myInsertQuery column:@"titre" value:@""];
	query = myInsertQuery.statement;
	[self.dbManager executeQuery:query];
	
	[fileManager createFileAtPath:soundPath contents:soundData attributes:nil];
	
}

-(void)deleteSound:(NSString*)soundName {
	NSString* query;
	
	ZIMSqlDeleteStatement *soundDeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[soundDeletequery table:@"sound"];
	[soundDeletequery where:@"soundName" operator:@"=" value:soundName];
	query = soundDeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	ZIMSqlDeleteStatement *articleSoundDeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[articleSoundDeletequery table:@"article_sound"];
	[articleSoundDeletequery where:@"soundName" operator:@"=" value:soundName];
	query = articleSoundDeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	NSString* filePath = [soundDirectoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",soundName]];
	[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

//TOOLS////////
- (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]
			];
}
///////////////

//NOTIFICATIONS
- (void)handleAddSoundToLibraryNotification:(NSNotification*)notification {
	NSDictionary* userInfo = notification.userInfo;
	NSData* soundData = (NSData*)userInfo[@"soundData"];
	[self addSoundToLibrary:soundData];
}

- (void)handleEditEndedNotification:(NSNotification*)note {
	[self updateSoundDirectoryContent];
	[self.soundDirectoryTableView reloadData];
}
///////////////

//BUTTON ACTIONS
- (IBAction)addSound:(id)sender {
	voiceRecorder = [voiceRecorderViewController alloc];
	[voiceRecorder showInView:self.view	animated:YES valueToEdit:[NSString stringWithFormat:@"index.png"] forSoundManager:true];
}
////////////////

//TABLE VIEW DELEGATE
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	[self updateSoundDirectoryContent];
	return soundDirectoryContent.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *simpleTableIdentifier = @"SimpleTableItem";
 
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
 
	if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
	}
	
	NSString* fileName = [soundDirectoryContent objectAtIndex:indexPath.row];
	
	ZIMSqlSelectStatement *mySoundSelectStatement = [[ZIMSqlSelectStatement alloc]init];
	[mySoundSelectStatement from:@"sound"];
	[mySoundSelectStatement where:@"soundName" operator:@"=" value:fileName];
	NSArray* dataSound = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[mySoundSelectStatement statement]]];
	NSString* titre = @"";
	if (dataSound.count > 0) {
		titre = [NSString stringWithFormat:@"%@", [[dataSound objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"titre"]]];
		if (titre.length == 0) {
			titre = @"Enregistrement sans titre";
		}
	}
	
	cell.textLabel.text = titre;
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	if (addSoundToArticle == true) {
		if (!(soundDirectoryContent.count < indexPath.row)) {
			NSString* soundName = [soundDirectoryContent objectAtIndex: indexPath.row];
			ZIMSqlInsertStatement *myInsertQuery = [[ZIMSqlInsertStatement alloc] init];
			id myId = [NSNumber numberWithInteger: articleId];
			[myInsertQuery into:@"article_sound"];
			[myInsertQuery column:@"soundName" value:soundName];
			[myInsertQuery column:@"articleId" value:myId];
			NSString* query = myInsertQuery.statement;
			[self.dbManager executeQuery:query];
			
			if (self.dbManager.affectedRows != 0) {
				[[NSNotificationCenter defaultCenter] postNotificationName:@"PhotoTerminated" object:self];
				[self closeThisView];
			}
		}
	}
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	// Return YES if you want the specified item to be editable.
	return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		if (!(soundDirectoryContent.count < indexPath.row)) {
			NSString* soundName = [soundDirectoryContent objectAtIndex: indexPath.row];
			[self deleteSound:soundName];
			[self.soundDirectoryTableView reloadData];
		}
	}
}
/////////////////////
@end
