//
//  viewInfo.m
//  melody app
//
//  Created by Odin on 12/09/2016.
//  Copyright © 2016 demain un autre jour. All rights reserved.
//

// !!! DO NOT TYPE CODE AFTER THE END OF FILE TAG !

/*

 +-------------------------------------------------------------------------+
 | This is the second view related class !                                 |
 +-------------------------------------------------------------------------+
 | - There is multiple methods related to the action buttons.              |
 |          - Disconnection                                                |
 |          - Write a new article                                          |
 +-------------------------------------------------------------------------+
 | - The others methods are for the tableView generation.                  |
 +-------------------------------------------------------------------------+
 | - the tableView display the writed file by "select" query on            |
 | the SQLITE 3 data base.                                                 |
 +-------------------------------------------------------------------------+

*/

#import "viewInfo.h"
#import "article.h"

@implementation viewInfo

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
	self.NewBlankArticle.hidden = 1;
	self.tablePeople.hidden = 0;
    self.tablePeople.delegate = self;
    self.tablePeople.dataSource = self;
    // Initialize the dbManager property.
    self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"baseData.sql"];
	[self loadData];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"returningToArticleList" object:nil];
}

-(void)createDirForImage :(NSString *)dirName
{
    NSString *path;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    path = [[paths objectAtIndex:0] stringByAppendingPathComponent:dirName];
    NSError *error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:path])    //Does directory already exist?
    {
        if (![[NSFileManager defaultManager] createDirectoryAtPath:path
                                       withIntermediateDirectories:NO
                                                        attributes:nil
                                                             error:&error])
        {
            //NSLog(@"Create directory error: %@", error);
        }
    }
    
}

- (IBAction)logs:(id)sender {
	[self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"logsView"] animated:YES];
}

- (IBAction)showMenu:(id)sender {
	
	UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:nil
															 delegate:self
													cancelButtonTitle:@"annuler"
											   destructiveButtonTitle:nil
													otherButtonTitles:@"Sonothèque", @"Logs", @"Déconnexion", nil];
	popup.tag = 1;
	[popup showInView:self.view];
	}

- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	switch (popup.tag) {
		case 1: {
			switch (buttonIndex) {
				case 0:
					popSoundManager = [soundManagerViewController alloc];
					[popSoundManager showInView:self.view animated:true toAddToArticle:false];
					break;
				case 1:
					//NSLog(@"logs");
					[self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"logsView"] animated:YES];
					break;
				case 2:
					//NSLog(@"decon");
					[self manageDeco];
					[self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"mainView"] animated:YES];
					
					break;
				}
			break;
		}
		default:
			break;
 }
}

//*****************************************//
//************  DISCONNECTION  ************//
//*****************************************//

-(void)manageDeco {
	NSUserDefaults *pref;
	pref=[NSUserDefaults standardUserDefaults];
	[pref setInteger:0 forKey:@"Ligne"];
	[pref synchronize];
}

//*****************************************//
//******** starting implementation ********//
//*****************************************//

-(void)loadData{

	//[self purgeLocalInfos];
	
    // Get the results.
    if (self.articleArray != nil) {
        self.articleArray = nil;
	}
	
	ZIMSqlSelectStatement *myArticleSelectStatement= [[ZIMSqlSelectStatement alloc]init];
	[myArticleSelectStatement from:@"article"];
	[myArticleSelectStatement column:@"titleZone"];
	[myArticleSelectStatement column:@"otherInfo"];
	[myArticleSelectStatement column:@"content"];
	[myArticleSelectStatement column:@"fileInfoID"];
	[myArticleSelectStatement column:@"chapo"];
	NSArray* SQLReturn = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[myArticleSelectStatement statement]]];
	[self setArticleObjetcArrayFromSQLArray:SQLReturn];
	
    if (self.articleArray.count == 0)
	{
		self.tablePeople.hidden = 1;
		self.NewBlankArticle.hidden = 0;
	}
	else {
		self.tablePeople.hidden = 0;
		self.NewBlankArticle.hidden = 1;
	}
    // Reload the table view.
    [self.tablePeople reloadData];
}

- (void) setArticleObjetcArrayFromSQLArray:(NSArray *) SQLArray {
	self.articleArray = [NSArray array];
	NSInteger indexOfTitle = [self.dbManager.arrColumnNames indexOfObject:@"titleZone"];
	NSInteger indexOfOtherÌnfo = [self.dbManager.arrColumnNames indexOfObject:@"otherInfo"];
	NSInteger indexOfContent = [self.dbManager.arrColumnNames indexOfObject:@"content"];
	NSInteger indexOfFileInfoID = [self.dbManager.arrColumnNames indexOfObject:@"fileInfoID"];
	NSInteger indexOfChapo = [self.dbManager.arrColumnNames indexOfObject:@"chapo"];
	for (NSArray* arrayArticle in SQLArray) {
		article* newArticle = [[article alloc] init];
		newArticle.fileInfoID = [[NSString stringWithFormat:@"%@", [arrayArticle objectAtIndex:indexOfFileInfoID]] intValue];
		newArticle.title = [NSString stringWithFormat:@"%@", [arrayArticle objectAtIndex:indexOfTitle]];
		newArticle.chapo = [NSString stringWithFormat:@"%@", [arrayArticle objectAtIndex:indexOfChapo]];
		newArticle.content = [NSString stringWithFormat:@"%@", [arrayArticle objectAtIndex:indexOfContent]];
		newArticle.otherInfos = [NSString stringWithFormat:@"%@", [arrayArticle objectAtIndex:indexOfOtherÌnfo]];
		self.articleArray = [self.articleArray arrayByAddingObject:newArticle];
	}
	
}

-(void) purgeLocalInfos {
	//PURGE AU LANCEMENT - BDD & files/////////////////////////////////////////////////////////////////////////////////////////////////////////
	 NSString *path;
	 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 1]];
	 BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 2]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 3]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 4]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 5]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 6]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 7]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 8]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 9]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 10]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 11]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	 path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", 12]];
	 success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	 
	 
	 NSString *query2 = @"delete from article";
	 // Execute the query.
	 [self.dbManager executeQuery:query2];
	 query2 = @"delete from catThem";
	 // Execute the query.
	 [self.dbManager executeQuery:query2];
	 query2 = @"delete from catGeo";
	 // Execute the query.
	[self.dbManager executeQuery:query2];
	query2 = @"delete from image";
	// Execute the query.
	[self.dbManager executeQuery:query2];
	query2 = @"delete from video";
	// Execute the query.
	[self.dbManager executeQuery:query2];
	
	 //PURGE AU LANCEMENT////////////////////////////////////////////////////////////////////////////////////////////////////////
}

- (IBAction)addNewRecord:(id)sender {
}

- (IBAction)NewBlankRecord:(id)sender {
	// Before performing the segue, set the -1 value to the recordIDToEdit. That way we'll indicate that we want to add a new record and not to edit an existing one.
	self.recordIDToEdit = -1;
	
	// Perform the segue.
	[self performSegueWithIdentifier:@"idSegueEditInfo" sender:self];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	article* articleAtRow = [self.articleArray objectAtIndex:indexPath.row];
	NSString* articleName = [NSString stringWithFormat:@"%@ %@", articleAtRow.title, [NSString stringWithFormat:@""]];
	NSString* articleChapo = [NSString stringWithFormat:@"%@ %@", articleAtRow.chapo, [NSString stringWithFormat:@""]];
	NSString* articleContent = [NSString stringWithFormat:@"%@ %@", articleAtRow.content, [NSString stringWithFormat:@""]];
	NSString* articleID = [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%d", articleAtRow.fileInfoID]];
	 
	// Dequeue the cell.
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"idCellRecord" forIndexPath:indexPath];
	NSString *pathData= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@/images", articleID]];
	BOOL fileExists=[[NSFileManager defaultManager] fileExistsAtPath:pathData];
	if (fileExists)
	{
		NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathData error:NULL];
		
		if (contents.count != 0)
		{
			NSString* finalPath = [NSString stringWithFormat:@"%@/%@", pathData, contents[0]];
			cell.imageView.image = [UIImage imageWithContentsOfFile:finalPath];
		}
		else
		{
			cell.imageView.image = NULL;
		}
	}
	
	// Set the loaded data to the appropriate cell labels.
	if ([articleName  isEqual: @" "]){
		cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", articleName, [NSString stringWithFormat:@"Article sans titre"]];
	}
	else {
		cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", articleName, [NSString stringWithFormat:@""]];
	}
	if (articleChapo.length > 1) {
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", articleChapo];
	} else {
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", articleContent];
	}
	
	return cell;
}

//*****************************************//
//********* tables rows counting **********//
//*****************************************//

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//*****************************************//
//********* numbers of subrows ************//
//*****************************************//

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.articleArray.count;
}

//*****************************************//
//************** size of celss ************//
//*****************************************//

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}

//*****************************************//
//****** accesory button parameters *******//
//*****************************************//

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // Get the record ID of the selected name and set it to the recordIDToEdit property.
	article* art = [self.articleArray objectAtIndex:indexPath.row];
    self.recordIDToEdit = art.fileInfoID;
    
    // Perform the segue.
    [self performSegueWithIdentifier:@"idSegueEditInfo" sender:self];
}

//*****************************************//
//************* editing infos *************//
//*****************************************//

-(void)editingInfoWasFinished{
    // Reload the data.
    [self loadData];
}

//*****************************************//
//******** mooving to edit panel **********//
//*****************************************//

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

//*****************************************//
//********** new article edition **********//
//*****************************************//

- (IBAction)writeArticle:(id)sender {
    // Before performing the segue, set the -1 value to the recordIDToEdit. That way we'll indicate that we want to add a new record and not to edit an existing one.
    self.recordIDToEdit = -1;
    
    // Perform the segue.
    [self performSegueWithIdentifier:@"idSegueEditInfo" sender:self];
}

//*****************************************//
//************ delete an article **********//
//*****************************************//

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the selected record.
		// Find the record ID.
		article* articleAtRow = [self.articleArray objectAtIndex:indexPath.row];
        int recordIDToDelete = articleAtRow.fileInfoID;
        // Prepare the query.
        NSString *query = [NSString stringWithFormat:@"delete from article where fileInfoID=%d", recordIDToDelete];
        // Execute the query.
		[self.dbManager executeQuery:query];
		// On supprime les entrées associant les article et les catégories -----------------------
		NSString* deleteQuery;
		id articleId = [NSNumber numberWithInteger: recordIDToDelete];
		ZIMSqlDeleteStatement *catgeodeletequery = [[ZIMSqlDeleteStatement alloc] init];
		[catgeodeletequery table:@"catGeo"];
		[catgeodeletequery where:@"fileInfoID" operator:@"=" value:articleId];
		deleteQuery = catgeodeletequery.statement;
		// Execute the query.
		[self.dbManager executeQuery:deleteQuery];
		
		ZIMSqlDeleteStatement *catthemdeletequery = [[ZIMSqlDeleteStatement alloc] init];
		[catthemdeletequery table:@"catThem"];
		[catthemdeletequery where:@"fileInfoID" operator:@"=" value:articleId];
		deleteQuery = catthemdeletequery.statement;
		// Execute the query.
		[self.dbManager executeQuery:deleteQuery];
		
		ZIMSqlDeleteStatement *imagedeletequery = [[ZIMSqlDeleteStatement alloc] init];
		[imagedeletequery table:@"image"];
		[imagedeletequery where:@"articleId" operator:@"=" value:articleId];
		deleteQuery = imagedeletequery.statement;
		// Execute the query.
		[self.dbManager executeQuery:deleteQuery];
		
		ZIMSqlDeleteStatement *videodeletequery = [[ZIMSqlDeleteStatement alloc] init];
		[videodeletequery table:@"video"];
		[videodeletequery where:@"articleId" operator:@"=" value:articleId];
		deleteQuery = videodeletequery.statement;
		// Execute the query.
		[self.dbManager executeQuery:deleteQuery];
		
		ZIMSqlDeleteStatement *sounddeletequery = [[ZIMSqlDeleteStatement alloc] init];
		[sounddeletequery table:@"article_sound"];
		[sounddeletequery where:@"articleId" operator:@"=" value:articleId];
		query = sounddeletequery.statement;
		// Execute the query.
		[self.dbManager executeQuery:query];
		//------------------------------------------------------------------------------------------
        // delete the image folder.
        NSString *path;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", recordIDToDelete]];
        BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        if (success == 1) {
            //NSLog(@"folder %@ successfuly deleted", path);
        }
        else {
            //NSLog(@"can't delete folder : %@", path);
        }
        // Reload the table view.
        [self loadData];
    }
}

@end

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
//                                END OF FILE                                         //
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
