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

/*
 
 +---------------------------------------------------------------+
 |  This class is for the delegate of geo cat searchBar          |
 +---------------------------------------------------------------+
 
 */

#import "searchBarDelegate.h"

@implementation searchBarDelegate {
	searchViewDelegate *svd;
	UITableView *myTableView;
	UICollectionView* myTagView;
	UIView *theView;
	NSInteger previousSearchSize;
	UISearchBar *mySearchBar;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

+(void) initialize
{
	
}

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

-  (id) initWithArticleId:(int)artId mainView:(UIView *)mainView refTable:(UITableView*)refTable tagView:(UICollectionView *)tagView {
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(catGeoHasBeenSelected) name:@"catGeoAdded" object:nil];
	self = [super init];
	self.articleId = artId;
	theView = mainView;
	myTagView = tagView;
	svd = [[searchViewDelegate alloc] initWithArticleId:self.articleId mainView:mainView tagView:myTagView];
	myTableView = refTable;
	myTableView.delegate = svd;
	myTableView.dataSource = svd;
	myTableView.hidden = 1;
	return self;
}

- (void)searchTableList : (NSString *) searchText
{
	NSString *searchText2 = [searchText lowercaseString];
	NSString* searchText2Tiret = [searchText2 stringByReplacingOccurrencesOfString:@" " withString:@"-"];
	NSString *xPathQuery = [NSString stringWithFormat:@"//thesaurus[@uniqueCode='GEO']//*[contains(@nomlc, '%@')]|//thesaurus[@uniqueCode='GEO']//*[contains(@nomlc, '%@')]", searchText2, searchText2Tiret];
	NSError *myError;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"cat.xml"]];
	NSData *data = [NSData dataWithContentsOfFile:fullPath options:NSDataReadingMappedIfSafe error:&myError];
	contentList = PerformXMLXPathQuery(data, xPathQuery);
	NSArray *matches = [contentList valueForKey:@"nodeAttributeArray"];
	NSArray *matches2 = [matches valueForKey:@"nodeContent"];
	filteredContentList = [[NSMutableArray alloc] initWithArray:matches2];
}

- (void)catGeoHasBeenSelected {
	[self searchBarTextDidEndEditing:mySearchBar];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
	@try {
		mySearchBar = searchBar;
		if (searchBar.text.length > 2) {
			isSearching = YES;
			NSUserDefaults *pref;
			pref=[NSUserDefaults standardUserDefaults];
			[pref setInteger:1 forKey:@"searchingCat"];
			[pref synchronize];
			//NSLog(@"searchingCat = 1");
			myTableView.hidden = 0;
			[[NSNotificationCenter defaultCenter] postNotificationName:@"enteringTagSearchBar" object:self];
		}
	}
	@catch (NSException *exception) {
		NSLog(@"%@", exception.reason);
	}
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	@try {
		if (searchText.length > 2) {
			if (previousSearchSize < 3) {
				[self searchBarTextDidBeginEditing:searchBar];
			}
			NSDictionary * userInfo = @{ @"toOrientation" : @"toOrientation" };
			[[NSNotificationCenter defaultCenter] postNotificationName:@"UIKeyboardWillHideNotification" object:nil userInfo:userInfo];
			//Remove all objects first.
			[filteredContentList removeAllObjects];
			if([searchText length] != 0) {
				isSearching = YES;
				[self searchTableList: searchBar.text];	}
			else {
				isSearching = NO;
			}
			[myTableView reloadData];
			[svd reload:contentList myFilteredList:filteredContentList];
		} else if (previousSearchSize > 2) {
			[[NSNotificationCenter defaultCenter] postNotificationName:@"exitingTagSearchBar" object:self];
			myTableView.hidden = 1;
		}
		previousSearchSize = searchText.length;
	}
	@catch (NSException *exception) {
		NSLog(@"%@", exception.reason);
	}
	
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
	@try {
		searchBar.text = @"";
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:.3];
		[UIView setAnimationBeginsFromCurrentState:TRUE];
		[UIView commitAnimations];
		NSUserDefaults *pref;
		pref=[NSUserDefaults standardUserDefaults];
		[pref setInteger:0 forKey:@"searchingCat"];
		[pref synchronize];
		[searchBar resignFirstResponder];
		[svd reload:contentList myFilteredList:filteredContentList];
		myTableView.hidden = 1;
		[[NSNotificationCenter defaultCenter] postNotificationName:@"exitingTagSearchBar" object:self];
	}
	@catch (NSException *exception) {
		NSLog(@"%@", exception.reason);
	}
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
	NSUserDefaults *pref;
	pref=[NSUserDefaults standardUserDefaults];
	[pref setInteger:0 forKey:@"searchingCat"];
	[pref synchronize];
	//NSLog(@"Cancel clicked");
	[svd reload:contentList myFilteredList:filteredContentList];
	myTableView.hidden = 1;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	//NSLog(@"Search Clicked");
	[svd reload:contentList myFilteredList:filteredContentList];
	[self searchTableList: searchBar.text];
}

@end
