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

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

/*

+----------------------------------------------------------------------------+
| - This file is the first login view linked class !                         |
|   The first methods are about the sha1 encryption                          |
|   of the XML formular generation.                                          |
+----------------------------------------------------------------------------+
| - Next it's about the HTML post by XML generation,                         |
|   parsing the webservice return, display error or                          |
|   entering session.                                                        |
+----------------------------------------------------------------------------+
| - Notice that there is an offline admin session                            |
|   for your tests.                                                          |
|                -> username: admin                                          |
|                -> password: thepasswd4adminsecurity                        |
+----------------------------------------------------------------------------+
| - Admin session allow you to test the application without connection       |
|   between the client and the webService access !                           |
|                                                                            |
| - There is an NSUserDefaults integer variable for connection status, when  |
|   this variable is setup to 42 the status is "connected", any another      |
|   value are for "disconnected".                                            |
+----------------------------------------------------------------------------+
| - The last step is the generation and parse of a personal info XML file.   |
+----------------------------------------------------------------------------+

*/

#import "ViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "contact.h"
#import "xmlParser.h"
#import "XMLWriter/XMLWriter.h"

@interface ViewController ()


@end
//ATTENTION MODIF A FAIRE AUSSI SUR EDITINGVIEW.M
//LOCAL//////////////////////////////////////////////////////////////////////
static NSString *_BO_URL= @"http://web.daj.demainunautrejour.com/gp/Melody/BackOffice/trunk/";
//PREPROLML//////////////////////////////////////////////////////////////////////
//static NSString *_BO_URL= @"http://melody.preprodlml.demainunautrejour.com/";
//DEV//////////////////////////////////////////////////////////////////////
//static NSString *_BO_URL= @"http://melodyjournal.daj.toulouse/";
//PROD//////////////////////////////////////////////////////////////////////
//static NSString *_BO_URL= @"http://correspondant.lamanchelibre.fr/";

@implementation ViewController
@synthesize login, passwd, errorMessage;

- (void)viewDidLoad {
    [super viewDidLoad];
    // checking user connexion status !
	NSUserDefaults *pref2;
	pref2=[NSUserDefaults standardUserDefaults];
	[pref2 setInteger:0 forKey:@"searchingCat"];
	[pref2 synchronize];
    NSUserDefaults *pref;
    pref=[NSUserDefaults standardUserDefaults];
	int status = (int) [pref integerForKey:@"Ligne"];
    if (status == 42) {
        [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"infoView"] animated:YES];
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

    //***************************************//
    //******* sha1 encrypting method ********//
    //***************************************//

- (NSString*) sha1:(NSString*)input {
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, data.length, digest);//warning detected here, implicit convertion
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return output;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	//NSLog(@"connection receive data !");
	// A response has been received, this is where we initialize the instance var you created
	// so that we can append data to it in the didReceiveData method
	// Furthermore, this method is called each time there is a redirect so reinitializing it
	// also serves to clear it
	_responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	//NSLog(@"connection receive data !");
	// Append the new data to the instance variable you declared
	[_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
				  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
	// Return nil to indicate not necessary to store a cached response for this connection
	return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	//NSLog(@"connection done !");
	NSString* xmlResponse=[[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
	NSString *correctString = [NSString stringWithCString:[xmlResponse cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
	//NSLog(@"\n\n response:\n\n: %@", correctString);
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"cat.xml"]];
	[correctString writeToFile:fullPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
	//NSLog(@"\n\nsession xml file for cathegories has been created\n\n");

	// The request is complete and data has been received
	// You can parse the stuff in your instance variable now
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	//NSLog(@"connection lost error !");
	// The request has failed for some reason!
	// Check the error var
}

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
//                            app start here                                        //
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//

-(IBAction)submit:(id)sender {
	
    //***************************************//
    //* starting get data from UI text zone *//
    //***************************************//
	//recupération des login et passwd depuis les champs textes de l'interface
    NSString* loginTxt = login.text;
    NSString* passwdTxt = passwd.text;
	//lancement de la fonction d'authentification
	[self authentificateUser:loginTxt passwd:passwdTxt];
}

-(Boolean)authentificateUser:(NSString *)loginTxt passwd:(NSString *)passwdTxt {
	//récupération des données d'authentification envoyé au webservice melody
	NSString* encryptedPasswd = [self sha1:passwdTxt];
	NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];//timestamp gen//
	NSNumber* timeStampObj = [NSNumber numberWithInt: timeStamp];
	NSString* token = [NSString stringWithFormat:@"%@melodyApplicationMobile%@", loginTxt, timeStampObj];//token gen//
	token = [self sha1:token];
	
	//***************************************//
	//starting comunication with web service!//
	//***************************************//
	//génération du xml de login envoyé au web service
	NSString* loginXmlPost = [self generateLoginXML:loginTxt encryptedPasswd:encryptedPasswd timestamp:timeStampObj token:token];
	
	NSString* urlString = [NSString stringWithFormat:@"%@webservice/APPLIMOBILE/login", _BO_URL];
	//envoie de la demande d'authentification au webservice qui retourne les données utilisateur
	NSString* xmlResponse=[self executePost:urlString XMLCommand:loginXmlPost];
	//affichage de la pop up en fonction du retour du webservice
	[self setAlertAccordingToLoginXMLResponse:xmlResponse loginTxt:loginTxt passwdTxt:passwdTxt];
	
	
	//***************************************//
	//** generation of seesionInfo.xml file *//
	//***************************************//
	//écriture du xml contenant les données  de l'utilisateur et de la session
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"sessionInfos.xml"]];
	[xmlResponse writeToFile:fullPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
	
	//***************************************//
	//*********** parsing xml data **********//
	//***************************************//
	//parsing des données renvoyé par lewebservice dans un object
	[self parseResponseXMLData:fullPath];
	
	//***************************************//
	//********* end of instructions *********//
	//***************************************//
	//récupération des thesaurus auquel l'utilisateur a droit
	NSString* categoriesXmlPost = [self generateCategoriesXML];
	[self getCategoriesInfos:categoriesXmlPost];
	
	return true;
}

-(NSString *)generateCategoriesXML{
	NSUserDefaults *pref=[NSUserDefaults standardUserDefaults];
	// obligé de convertir d'abord en int avant de reconvertir en string sinon l'appli plante pour une sombre histoire de caractère d'echappement dans le xmlwriter
	NSInteger userIdI = [[pref objectForKey:@"userId"] integerValue];
	NSString* userId = [NSString stringWithFormat: @"%ld", (long)userIdI];
	// start writing XML
	XMLWriter* xmlWriter = [[XMLWriter alloc]init];
	[xmlWriter writeStartDocumentWithEncodingAndVersion:@"UTF-8" version:@"1.0"];
	[xmlWriter writeStartElement:@"content"];
	[xmlWriter writeStartElement:@"userId"];
	[xmlWriter writeCharacters:userId];
	[xmlWriter writeEndElement];
	[xmlWriter writeEndElement];
	[xmlWriter writeEndDocument];
	
	// get the resulting XML string
	NSString* xml = [xmlWriter toString];
	
	return xml;
}
-(NSString *)generateLoginXML:(NSString *)loginTxt encryptedPasswd:(NSString *)encryptedPasswd timestamp:(NSNumber *)timestamp token:(NSString *)token {
	// start writing XML
	XMLWriter* xmlWriter = [[XMLWriter alloc]init];
	[xmlWriter writeStartDocumentWithEncodingAndVersion:@"UTF-8" version:@"1.0"];
	[xmlWriter writeStartElement:@"content"];
	[xmlWriter writeStartElement:@"login"];
	[xmlWriter writeCharacters:loginTxt];
	[xmlWriter writeEndElement];
	[xmlWriter writeStartElement:@"pwd"];
	[xmlWriter writeCharacters:encryptedPasswd];
	[xmlWriter writeEndElement];
	[xmlWriter writeStartElement:@"timestamp"];
	[xmlWriter writeCharacters:[timestamp stringValue]];
	[xmlWriter writeEndElement];
	[xmlWriter writeStartElement:@"token"];
	[xmlWriter writeCharacters:token];
	[xmlWriter writeEndElement];
	[xmlWriter writeEndElement];
	[xmlWriter writeEndDocument];
	
	// get the resulting XML string
	NSString* xml = [xmlWriter toString];
	
	return xml;
}

-(NSString *)executePost:(NSString *)url XMLCommand:(NSString *)XMLCommand {
	
	NSData *postData = [XMLCommand dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	
	NSString *postLength = [NSString stringWithFormat:@"%lu", [postData length]];
	//NSLog(@"%@", urlString);
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
									initWithURL:[NSURL
												 URLWithString:url]];
	[request setHTTPMethod:@"POST"];
	[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:postData];
	
	//***************************************//
	//*** returning data from the server ****//
	//***************************************//
	
	NSHTTPURLResponse *response = nil;
	NSError *error = nil;
	NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	NSString* xmlResponse=[[NSString alloc] initWithData:respData encoding:NSASCIIStringEncoding];
	
	return xmlResponse;
}

-(void)getCategoriesInfos:(NSString *)categoriesXML {
	// Create the request.
	NSData *postData = [categoriesXML dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	
	NSString *postLength = [NSString stringWithFormat:@"%lu", [postData length]];
	NSString *urlCat = [NSString stringWithFormat:@"%@webservice/APPLIMOBILE/getCategories", _BO_URL];
	
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
									 initWithURL:[NSURL
												  URLWithString:urlCat]];
	[request setHTTPMethod:@"POST"];
	[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:postData];
	// Create url connection and fire request
	
	NSHTTPURLResponse *response = nil;
	NSError *error = nil;
	NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	NSString* xmlResponse=[[NSString alloc] initWithData:respData encoding:NSASCIIStringEncoding];
	
	NSString *correctString = [NSString stringWithCString:[xmlResponse cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"cat.xml"]];
	[correctString writeToFile:fullPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

-(void)setAlertAccordingToLoginXMLResponse:(NSString *)xmlResponse loginTxt:(NSString *)loginTxt passwdTxt:(NSString *)passwdTxt {
	//utilisateur admin
	if ([loginTxt isEqualToString:@"admin"] && [passwdTxt isEqualToString:@"thepasswd4adminsecurity"]){
		//NSLog(@"\nadmin connected\n\n");
		errorMessage.text = @"";
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Admin connexion"
														message:@"you are on an admin session !" delegate:self cancelButtonTitle:@"ok"
											  otherButtonTitles:nil, nil];
		[alert show];
		[self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"infoView"] animated:YES];
	//pas de message d'erreur et pas d'info sur l'utilisateur = pas de connexion
	} else if (([xmlResponse rangeOfString:@"<error>"].location == NSNotFound) && ([xmlResponse rangeOfString:@"<userInfos>"].location == NSNotFound)){
		//NSLog(@"\nconnexion lost!\n\n");
		errorMessage.text = @"";
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erreur"
														message:@"pas de connexion internet" delegate:self cancelButtonTitle:@"ok"
											  otherButtonTitles:nil, nil];
		[alert show];
	}
	//pas d'erreur tout va bien
	else if ([xmlResponse rangeOfString:@"<error>"].location == NSNotFound) {
		errorMessage.text = @"";
		//setting user connection status to "CONNECTED" !
		NSUserDefaults *pref;
		pref=[NSUserDefaults standardUserDefaults];
		[pref setInteger:42 forKey:@"Ligne"];
		[pref synchronize];
		[self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"infoView"] animated:YES];
	}
	else {
		errorMessage.text = @"";
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erreur"
														message:@"mdp / login invalide" delegate:self cancelButtonTitle:@"ok"
											  otherButtonTitles:nil, nil];
		[alert show];
	}
}

-(void)parseResponseXMLData:(NSString *)path{
	
	NSString *filePath = [NSString stringWithFormat:@"%@", path];
	NSURL *fileURL = [NSURL URLWithString:filePath];
	
	XMLToObjectParser *myParser = [[XMLToObjectParser alloc]
								   parseXMLAtURL:filePath toObject:@"userInfos" parseError:nil];
	//parsing des infos retournées par le xml
	for(int i = 0; i < [[myParser items] count]; i++) {
		NSString *userId = [(userInfos *)[[myParser items] objectAtIndex:i] id];
		int value = [userId intValue];
		NSUserDefaults *pref;
		NSString *signatureValue = [(userInfos *)[[myParser items] objectAtIndex:i] signature];
		NSString *canalValue = [(userInfos *)[[myParser items] objectAtIndex:i] canalId];
		//NSLog(@"canal value %@", canalValue);
		pref=[NSUserDefaults standardUserDefaults];
		[pref setInteger:value forKey:@"userId"];
		[pref setValue:signatureValue forKey:@"signature"];
		//[pref setValue:canalValue forKey:@"canalId"];
		[pref synchronize];
	}
}

@end

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