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

/*

 +---------------------------------------------------------------+
 |  This class is for the delegate of photo TableView            |
 +---------------------------------------------------------------+
 
*/
#import "tableViewDelegate.h"
#import <AVFoundation/AVFoundation.h>

@implementation tableViewDelegate

+(void) initialize
{
	
}

-(id) init
{
	self = [super init];
	return self;
}

-(id) initWithArticleId:(int)artId mainView:(UIView *)mainView
{
	self = [super init];
	self.articleId = artId;
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"PhotoTerminated" object:nil];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"releaseSound" object:self];
	[self loadContents];
	myView = mainView;
	self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"baseData.sql"];
	return self;
}

-(void) loadContents {
	self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"baseData.sql"];
	
	NSMutableArray* contentArray = [[NSMutableArray alloc] init];
	NSString *imagePathData= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/images", self.articleId]];
	NSArray* imageContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:imagePathData error:NULL];
	for (id fileName in imageContents) {
		[contentArray addObject:[NSString stringWithFormat:@"images/%@", fileName]];
	}
	
	NSString *videoPathData= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/videos", self.articleId]];
	NSArray* videoContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:videoPathData error:NULL];
	
	for (id fileName in videoContents) {
		[contentArray addObject:[NSString stringWithFormat:@"videos/%@", fileName]];
	}
	
	id myId = [NSNumber numberWithInteger: self.articleId];
	ZIMSqlSelectStatement *articleSoundsSelectStatement = [[ZIMSqlSelectStatement alloc]init];
	[articleSoundsSelectStatement from:@"article_sound"];
	[articleSoundsSelectStatement where:@"articleId" operator:@"=" value:myId];
	NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:articleSoundsSelectStatement.statement]];
	NSUInteger soundNameIndex = [self.dbManager.arrColumnNames indexOfObject:@"soundName"];
	
	for (id result in results) {
		[contentArray addObject:[NSString stringWithFormat:@"sounds/%@", [result objectAtIndex:soundNameIndex]]];
	}
	
	contents = contentArray;
}

- (void)reload {
	[self loadContents];
	[ref reloadData];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)handleNotification:(NSNotification*)note {
	[self reload];
}


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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString* contentRow = contents[indexPath.row];
	NSString* fileDirectory = [contentRow componentsSeparatedByString:@"/"][0];
	NSString* fileName = [contentRow componentsSeparatedByString:@"/"][1];
	ref = tableView;
	UITableViewCell *cell;
	cell.translatesAutoresizingMaskIntoConstraints = FALSE;
	NSString *articlePath= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d", self.articleId]];
	static NSString *CellIdentifier = @"imageCell";
	cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:10];
	UILabel *imageName = (UILabel *)[cell viewWithTag:11];
	NSString *query;
	ZIMSqlSelectStatement *mySelectStatement = [[ZIMSqlSelectStatement alloc]init];
	if ([fileDirectory  isEqual: @"images"]) {
		[mySelectStatement from:@"image"];
		[mySelectStatement where:@"imageName" operator:@"=" value:fileName];
		query = [mySelectStatement statement];
		// Load the relevant data.
		NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
		if (results.count == 0) {
			NSLog(@"cound not execute query");
		}
		else{
			imageName.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"legend"]];
		}
		if ([[NSString stringWithFormat:@"%@/%@/%@",articlePath ,fileDirectory, fileName] rangeOfString:@".jpg"].location == NSNotFound) {
			return cell;
		}
		recipeImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@/%@/%@",articlePath ,fileDirectory, fileName]];
		cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:fileName]];
	} else if ([fileDirectory  isEqual: @"videos"]) {
		[mySelectStatement from:@"video"];
		[mySelectStatement where:@"videoName" operator:@"=" value:fileName];
		query = [mySelectStatement statement];
		// Load the relevant data.
		NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
		if (results.count == 0) {
			NSLog(@"cound not execute query");
		}
		else{
			imageName.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"titre"]];
		}
		NSURL* videoUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@/%@",articlePath, fileDirectory, fileName]];
		UIImage* videoThumbnail = [self generateImageFromVideoUrl:videoUrl];
		recipeImageView.image = videoThumbnail;
		cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:fileName]];
	} else if ([fileDirectory  isEqual: @"sounds"]) {
		[mySelectStatement from:@"sound"];
		[mySelectStatement where:@"soundName" operator:@"=" value:fileName];
		query = [mySelectStatement statement];
		// Load the relevant data.
		NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
		if (results.count == 0) {
			NSLog(@"cound not execute query");
		}
		else{
			imageName.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"titre"]];
		}
		recipeImageView.image = [UIImage imageNamed:@"soundIcon"];
		cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:fileName]];
	}
	return cell;
}

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	// Return the number of sections.
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	[self loadContents];
	return [contents count];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
	id myId = [NSNumber numberWithInteger: self.articleId];
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		NSString* contentRow = contents[indexPath.row];
		NSString* fileDirectory = [contentRow componentsSeparatedByString:@"/"][0];
		NSString* fileName = [contentRow componentsSeparatedByString:@"/"][1];
		
		NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/%@/%@", self.articleId, fileDirectory, fileName]];
		NSFileManager *fileManager = [NSFileManager defaultManager];
		[fileManager removeItemAtPath: fullPath error:NULL];
		NSString *query; 		ZIMSqlDeleteStatement *myDeleteStatement = [[ZIMSqlDeleteStatement alloc] init];
		if ([fileDirectory  isEqual: @"images"]) {
			[myDeleteStatement table:@"image"];
			[myDeleteStatement where:@"imageName" operator:@"=" value:fileName];
		} else if ([fileDirectory  isEqual: @"videos"]) {
			[myDeleteStatement table:@"video"];
			[myDeleteStatement where:@"videoName" operator:@"=" value:fileName];
		} else if ([fileDirectory  isEqual: @"sounds"]) {
			[myDeleteStatement table:@"article_sound"];
			[myDeleteStatement where:@"soundName" operator:@"=" value:fileName];
			[myDeleteStatement where:@"articleId" operator:@"=" value:myId];
		}
		query = myDeleteStatement.statement;
		[self.dbManager executeQuery:query];
		//NSLog(@"image removed");
	}
	[self reload];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	if (indexPath == nil){
		NSLog(@"couldn't find index path");
	} else {
		NSString* contentRow = contents[indexPath.row];
		NSString* fileDirectory = [contentRow componentsSeparatedByString:@"/"][0];
		NSString* fileName = [contentRow componentsSeparatedByString:@"/"][1];
		if ( [fileDirectory  isEqual: @"images"]) {
			popImage = [showImageViewViewController alloc];
			popImage.mediaType = @"image";
			[popImage showInView:myView	animated:YES valueToEdit:fileName articleId:self.articleId isForLibrary:false];
			[self loadContents];
			//NSLog(@"\n\n%@\n\n",contents);
			[tableView reloadData];
		} else if ( [fileDirectory  isEqual: @"videos"]) {
			popImage = [showImageViewViewController alloc];
			popImage.mediaType = @"video";
			[popImage showInView:myView	animated:YES valueToEdit:fileName articleId:self.articleId isForLibrary:false];
			[self loadContents];
			//NSLog(@"\n\n%@\n\n",contents);
			[tableView reloadData];
		} else if ( [fileDirectory  isEqual: @"sounds"]) {
			popImage = [showImageViewViewController alloc];
			popImage.mediaType = @"sound";
			[popImage showInView:myView	animated:YES valueToEdit:fileName articleId:self.articleId isForLibrary:false];
			[self loadContents];
			//NSLog(@"\n\n%@\n\n",contents);
			[tableView reloadData];
		}
	}
}

@end
