//
//  showImageViewViewController.m
//  melody app
//
//  Created by Odin on 07/11/2016.
//  Copyright © 2016 demain un autre jour. All rights reserved.
//
/*

+---------------------------------------------------------------+
| This class is for displaying image informations.				|
+---------------------------------------------------------------+
| You have to use the showInView method to start displaying view|
+---------------------------------------------------------------+


*/
#import "editingView.h"
#import "showImageViewViewController.h"
#import "ZIMSqlStatement.h"
#import <AVFoundation/AVFoundation.h>

@interface showImageViewViewController () {
	NSString *fileName;
	NSArray *infos;
	NSArray *articleId;
}

@end

@implementation showImageViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	CGRect screen = [[UIScreen mainScreen] bounds];
	self.view.frame = screen;
	self.view.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:.6];
	self.legend.delegate = self;
	self.credit.delegate = self;
	self.deleteButton.layer.borderWidth = 1.0f;
	self.deleteButton.layer.borderColor = [[UIColor grayColor] CGColor];
	self.deleteButton.layer.cornerRadius = 5.0;
	self.okButton.layer.borderWidth = 1.0f;
	self.okButton.layer.borderColor = [[UIColor grayColor] CGColor];
	self.okButton.layer.cornerRadius = 5.0;
	self.popUpView.layer.cornerRadius = 5;
	self.popUpView.layer.shadowOpacity = 0.8;
	self.popUpView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
	self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"baseData.sql"];
	if ([self.mediaType  isEqual: @"video"]) {
		self.credit.hidden = true;
		self.legend.placeholder = @"Titre de la video";
	}
	if ([self.mediaType  isEqual: @"sound"]) {
		self.credit.hidden = true;
		self.legend.placeholder = @"Titre du fichier";
	}
	
	
	[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(orientationChanged:)
												 name:UIDeviceOrientationDidChangeNotification
											   object:nil];
	// Do any additional setup after loading the view from its nib.
}

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

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}

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

/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)okSender:(id)sender {
	NSString *query;
	
	if ([self.mediaType  isEqual: @"sound"]) {		
		ZIMSqlSelectStatement *SoundsSelectStatement = [[ZIMSqlSelectStatement alloc]init];
		[SoundsSelectStatement from:@"sound"];
		[SoundsSelectStatement where:@"titre" operator:@"=" value:self.legend.text];
		NSArray* data = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[SoundsSelectStatement statement]]];
		
		if (data.count > 0) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Titre : %@", self.legend.text]
															message:@"Un son avec ce titre existe déjà" delegate:self cancelButtonTitle:@"OK"
												  otherButtonTitles:nil, nil];
			[alert show];
			return;
		}
	}
	
	ZIMSqlUpdateStatement *myUpdatequery = [[ZIMSqlUpdateStatement alloc] init];
	if ([self.mediaType  isEqual: @"image"]) {
		[myUpdatequery table:@"image"];
		[myUpdatequery where:@"imageName" operator:@"=" value:fileName];
		[myUpdatequery column:@"legend" value:self.legend.text];
		[myUpdatequery column:@"credit" value:self.credit.text];
		query = myUpdatequery.statement;
		NSLog(@"query is here :%@", myUpdatequery.statement);
		[self.dbManager executeQuery:query];
		if (self.dbManager.affectedRows != 0) {
			NSLog(@"Query was executed successfully hahaha. Affected rows = %d", self.dbManager.affectedRows);
			// Inform the delegate that the editing was finished.
		}
		else{
			NSLog(@"Could not execute the query.");
		}
	} else if ([self.mediaType  isEqual: @"video"]) {
		[myUpdatequery table:@"video"];
		[myUpdatequery where:@"videoName" operator:@"=" value:fileName];
		[myUpdatequery column:@"titre" value:self.legend.text];
		query = myUpdatequery.statement;
		NSLog(@"query is here :%@", myUpdatequery.statement);
		[self.dbManager executeQuery:query];
		if (self.dbManager.affectedRows != 0) {
			NSLog(@"Query was executed successfully hahaha. Affected rows = %d", self.dbManager.affectedRows);
			// Inform the delegate that the editing was finished.
		}
		else{
			NSLog(@"Could not execute the query.");
		}
	} else if ([self.mediaType  isEqual: @"sound"]) {
		[myUpdatequery table:@"sound"];
		[myUpdatequery where:@"soundName" operator:@"=" value:fileName];
		[myUpdatequery column:@"titre" value:self.legend.text];
		query = myUpdatequery.statement;
		NSLog(@"query is here :%@", myUpdatequery.statement);
		[self.dbManager executeQuery:query];
		if (self.dbManager.affectedRows != 0) {
			NSLog(@"Query was executed successfully hahaha. Affected rows = %d", self.dbManager.affectedRows);
			// Inform the delegate that the editing was finished.
		}
		else{
			NSLog(@"Could not execute the query.");
		}
	}
	[[NSNotificationCenter defaultCenter] postNotificationName:@"PhotoTerminated" object:self];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"releaseSound" object:self];
	[self removeAnimate];
}

- (IBAction)deleteImage:(id)sender {
	id myId = [NSNumber numberWithInteger: articleId];
	if ([self.mediaType  isEqual: @"image"]) {
		NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@/images/%@", articleId, fileName]];
		NSFileManager *fileManager = [NSFileManager defaultManager];
		[fileManager removeItemAtPath: fullPath error:NULL];
		NSString *query;
		ZIMSqlDeleteStatement *myDeleteStatement = [[ZIMSqlDeleteStatement alloc] init];
		[myDeleteStatement table:@"image"];
		[myDeleteStatement where:@"imageName" operator:@"=" value:fileName];
		query = myDeleteStatement.statement;
		[self.dbManager executeQuery:query];
		NSLog(@"image removed");
		[self removeAnimate];
	} else if ([self.mediaType  isEqual: @"video"]) {
		NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@/videos/%@", articleId, fileName]];
		NSFileManager *fileManager = [NSFileManager defaultManager];
		[fileManager removeItemAtPath: fullPath error:NULL];
		NSString *query;
		ZIMSqlDeleteStatement *myDeleteStatement = [[ZIMSqlDeleteStatement alloc] init];
		[myDeleteStatement table:@"video"];
		[myDeleteStatement where:@"videoName" operator:@"=" value:fileName];
		query = myDeleteStatement.statement;
		[self.dbManager executeQuery:query];
		NSLog(@"video removed");
		[self removeAnimate];
	} else if ([self.mediaType  isEqual: @"sound"]) {
		NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/sounds/%@", fileName]];
		NSFileManager *fileManager = [NSFileManager defaultManager];
		[fileManager removeItemAtPath: fullPath error:NULL];
		NSString *query;
		ZIMSqlDeleteStatement *myDeleteStatement = [[ZIMSqlDeleteStatement alloc] init];
		[myDeleteStatement table:@"article_sound"];
		[myDeleteStatement where:@"soundName" operator:@"=" value:fileName];
		[myDeleteStatement where:@"articleId" operator:@"=" value:myId];
		query = myDeleteStatement.statement;
		[self.dbManager executeQuery:query];
		NSLog(@"sound removed");
		[self removeAnimate];
	}
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
	editingView *editInfoViewController = [segue destinationViewController];
	editInfoViewController.delegate = self;
}

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

- (void)removeAnimate
{
	[UIView animateWithDuration:.25 animations:^{
		self.view.transform = CGAffineTransformMakeScale(1.3, 1.3);
		self.view.alpha = 0.0;
	} completion:^(BOOL finished) {
		if (finished) {
			// receive MyNotification events from any object
			// create a notification
			[[NSNotificationCenter defaultCenter] postNotificationName:@"PhotoTerminated" object:self];
			[[NSNotificationCenter defaultCenter] postNotificationName:@"releaseSound" object:self];
			[self.view removeFromSuperview];
		}
	}];
}

- (void)showInView:(UIView *)aView animated:(BOOL)animated valueToEdit:(NSString*) valueEdit articleId:(int) myArticleId isForLibrary:(BOOL)isForLibrary
{
	[aView addSubview:self.view];
	if (animated) {
		fileName = valueEdit;
		if ([self.mediaType  isEqual: @"image"]) {
			NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/images/%@", myArticleId, fileName]];
			NSData *imgData = [NSData dataWithContentsOfFile:imagePath];
			NSLog(@"here you are %@", fileName);
			self.imageView.image = [[UIImage alloc] initWithData:imgData];
			[self showAnimate];
			[self loadInfoToEdit];
			[self setCreditText];
		} else if ([self.mediaType  isEqual: @"video"]) {
			NSString *videoPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/videos/%@", myArticleId, fileName]];
			NSLog(@"here you are %@", fileName);
			NSURL* videoUrl = [NSURL fileURLWithPath:videoPath];
			self.imageView.image = [self generateImageFromVideoUrl:videoUrl];
			[self showAnimate];
			[self loadInfoToEdit];
		} else if ([self.mediaType  isEqual: @"sound"]) {
			self.imageView.image = [UIImage imageNamed:@"soundIcon"];
			[self showAnimate];
			[self loadInfoToEdit];
		}
	}
}

- (void)showInView:(UIView *)aView animated:(BOOL)animated valueToEdit:(NSString*) valueEdit isForLibrary:(BOOL)isForLibrary
{
	[aView addSubview:self.view];
	if (animated) {
		fileName = valueEdit;
		if ([self.mediaType  isEqual: @"sound"]) {
			self.imageView.image = [UIImage imageNamed:@"soundIcon"];
			[self showAnimate];
			[self loadInfoToEdit];
		}
	}
}


-(UIImage*)generateImageFromVideoUrl:(NSURL*)videoUrl
{
	AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil];
	AVAssetImageGenerator  *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
	NSError *error = NULL;
	CMTime time = CMTimeMake(1, 1);
	CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&error];
	NSLog(@"error==%@, Refimage==%@", error, refImg);
	
	UIImage *FrameImage= [[UIImage alloc] initWithCGImage:refImg];
	return FrameImage;
}

-(void) setCreditText {
	if (self.credit.text.length == 0) {
		NSUserDefaults *pref;
		pref = [NSUserDefaults standardUserDefaults];
		self.credit.text = [pref stringForKey:@"signature"];
	}
}

-(void)loadInfoToEdit{
	// Create the query.
	NSString *query;
	ZIMSqlSelectStatement *mySelectStatement = [[ZIMSqlSelectStatement alloc]init];
	if ([self.mediaType  isEqual: @"image"]) {
		[mySelectStatement from:@"image"];
		[mySelectStatement where:@"imageName" operator:@"=" value:fileName];
		query = [mySelectStatement statement];
		NSLog(@"query is there : %@", query);
		// Load the relevant data.
		NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
		if (results.count == 0) {
			NSLog(@"cound not execute query");
		}
		else{
		NSLog(@"results = %@", results);
		// Set the loaded data to the textfields.
		self.legend.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"legend"]];
		self.credit.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"credit"]];
		articleId = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"articleId"]];
		if ([self.credit.text  isEqual: @""]) {
			NSUserDefaults *pref;
			pref=[NSUserDefaults standardUserDefaults];
			NSString* status = [pref valueForKey:@"signature"];
			self.credit.text = status;
			}
		}
	} else if ([self.mediaType  isEqual: @"video"]) {
		[mySelectStatement from:@"video"];
		[mySelectStatement where:@"videoName" operator:@"=" value:fileName];
		query = [mySelectStatement statement];
		NSLog(@"query is there : %@", query);
		// Load the relevant data.
		NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
		if (results.count == 0) {
			NSLog(@"cound not execute query");
		}
		else{
			NSLog(@"results = %@", results);
			// Set the loaded data to the textfields.
			self.legend.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"titre"]];
			articleId = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"articleId"]];
		}
	} else if ([self.mediaType  isEqual: @"sound"]) {
		[mySelectStatement from:@"sound"];
		[mySelectStatement where:@"soundName" operator:@"=" value:fileName];
		query = [mySelectStatement statement];
		NSLog(@"query is there : %@", query);
		// Load the relevant data.
		NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
		if (results.count == 0) {
			NSLog(@"cound not execute query");
		}
		else{
			NSLog(@"results = %@", results);
			// Set the loaded data to the textfields.
			self.legend.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"titre"]];
		}
	}
}

@end
