//
//  LoginViewController.m
//  VisIVOSmart
//
//  Created by Fabio Vitello on 18/10/11.
//  Copyright (c) 2011 nothing. All rights reserved.
//

#import "LoginViewController.h"
#import "FileViewController.h"
#import "ImportViewController.h"
#import "FilterViewController.h"
#import "OtherViewController.h"
#import "ViewerViewController.h"

#import "NSString+SHA1Base64.h"

#import <CommonCrypto/CommonHMAC.h>

@implementation LoginViewController

- (id)init
{
    self = [super init];
    if (self) {
            
        appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

        
        [super initWithStyle:UITableViewStyleGrouped];
        self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
        
        
        dataSource = [[NSMutableDictionary alloc] init];
 
        
        //Initialize UITextField (username e password)
        usernameField=[[UITextField alloc] initWithFrame:CGRectMake(10, 5, 280, 40)];
        passwordField=[[UITextField alloc] initWithFrame:CGRectMake(10, 5, 280, 40)];
        
        //Set properties for usernameField 
        usernameField.backgroundColor=[UIColor clearColor];
        usernameField.placeholder=@"Username";
        usernameField.textAlignment=UITextAlignmentLeft;
        usernameField.clearButtonMode = UITextFieldViewModeWhileEditing;
        usernameField.returnKeyType=UIReturnKeyDone;
        usernameField.adjustsFontSizeToFitWidth=YES;
        usernameField.autocorrectionType=UITextAutocorrectionTypeNo;
        usernameField.autocapitalizationType= UITextAutocapitalizationTypeNone;
      
        //Set properties for passwordField 
        passwordField.backgroundColor=[UIColor clearColor];
        passwordField.placeholder=@"Password";
        passwordField.textAlignment=UITextAlignmentLeft;
        passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
        passwordField.returnKeyType=UIReturnKeyDone;
        passwordField.adjustsFontSizeToFitWidth=YES;
        passwordField.autocorrectionType=UITextAutocorrectionTypeNo;
        passwordField.autocapitalizationType= UITextAutocapitalizationTypeNone;
        passwordField.secureTextEntry=YES;        
        
        //read, if stored, username and password from NSUserDefault
        usernameField.text=[[NSUserDefaults standardUserDefaults] objectForKey:@"usern"];
        passwordField.text=[[NSUserDefaults standardUserDefaults] objectForKey:@"passw"];
      
        elements=[NSArray arrayWithObjects:usernameField,passwordField,nil];
      
        [self.view setUserInteractionEnabled:YES];
        
        return self;
        
    }
    return self;
}



-(void) login
{
    
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;

    //if text field are empty
    if ((usernameField.text==nil) || (passwordField.text==nil)) {
        
        NSString *errorString = NSLocalizedString(@"insert_data",@"");
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:errorString 
                                                                 delegate:nil 
                                                        cancelButtonTitle:nil 
                                                   destructiveButtonTitle:@"OK"  
                                                        otherButtonTitles:nil]; 
        [actionSheet showInView:[[self view] window]];
        [actionSheet release]; 
        
        [usernameField resignFirstResponder];
        [passwordField resignFirstResponder];
        return;
        
    }
    else 
    {
        //"Read" inseret data
        username=[[NSString alloc] initWithFormat:@"%@", usernameField.text];
        password=[[NSString alloc] initWithFormat:@"%@", passwordField.text];
      
        
        NSString *b64_hash = [password B64SHA1URLEncoded];

        //UIAlertView with UIActivityIndicator
        alert=[[UIAlertView alloc] initWithTitle: NSLocalizedString(@"login",@"") message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        
        [alert show];
        
        float diff=screenSize.width-alert.bounds.size.width;
          
        indicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        indicator.center =CGPointMake(screenSize.width/2-diff/2,70);
        [indicator startAnimating];
        [alert addSubview:indicator];
        [indicator release];
        

        
        
        NSString *url= [NSString stringWithFormat:@"%@/VisIVOSmart/login.php",[appDelegate.mySetting objectForKey:@"SiteUrl"]];
        
        //Connection
        logConnection=[[LoginConnection alloc]initWithReference:url username:username password:b64_hash];

        logConnection.delegate = self;
        logConnection.delegateMethod = @selector(parseData:);
        logConnection.delegateErrorMethod=@selector(parseError:);
        [logConnection makePostRequest];
        
        
        //Hide keyboard
        [usernameField resignFirstResponder];
        [passwordField resignFirstResponder];
        
        passwordField.text = nil;
        
    }

}


//if there were errors in the connection
-(void)parseError:(id)sender
{
    
	//Alert the user that there was an error connecting to server
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle: NSLocalizedString(@"conn_error",@"") 
															 delegate:nil 
													cancelButtonTitle:@"OK" 
											   destructiveButtonTitle:nil 
													otherButtonTitles:nil]; 
	
	[alert dismissWithClickedButtonIndex:0 animated:YES];
	
	[actionSheet showInView:[[self view] window]];
	[actionSheet release]; 
	    
}


//if there were no errors in the connection
-(void)parseData:(id)sender {
	
	LoginConnection *tmpConnection = (LoginConnection *)sender;
	
    [dataSource setDictionary:tmpConnection.receivedDictionary ];
    
    
	//"Results" of connection
	NSString *loginStatus = [dataSource objectForKey:@"status"];	
    
    //Dismiss "login alert"
	[alert dismissWithClickedButtonIndex:0 animated:YES];
    
	//if connection result are "OK", login credentials are correct
	if ([loginStatus isEqualToString:@"OK"])
    {
	    //Store credential on device
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:username forKey:@"usern"];
        [defaults setObject:password forKey:@"passw"];
		[defaults synchronize];

      
        //Create all tab for application
        FileViewController *fileViewController=[[FileViewController alloc]initWithTitle:@"Data" andIcon:@"file.png"\
                                                                              andUserId:[dataSource objectForKey:@"user_id"] andUserName:[dataSource objectForKey:@"name"]];
        ImportViewController *importViewController=[[ImportViewController alloc]initWithTitle:@"Import" andIcon:@"importer.png"];
        FilterViewController *filterViewController=[[FilterViewController alloc]initWithTitle:@"Filter" andIcon:@"filters.png"];
        ViewerViewController *viewerViewController=[[ViewerViewController alloc]initWithTitle:@"Viewer" andIcon:@"viewer.png"];
        OtherViewController *otherViewController=[[OtherViewController alloc]initWithTitle:@"More" andIcon:@"viewer.png"];
        OtherViewController *otherViewController1=[[OtherViewController alloc]initWithTitle:@"More" andIcon:@"viewer.png"];
        OtherViewController *otherViewController2=[[OtherViewController alloc]initWithTitle:@"More" andIcon:@"viewer.png"];
        OtherViewController *otherViewController3=[[OtherViewController alloc]initWithTitle:@"More" andIcon:@"viewer.png"];
        
        
        
        UINavigationController *navControllerFile=[[UINavigationController alloc] initWithRootViewController:fileViewController];
        UINavigationController *navControllerImpo=[[UINavigationController alloc] initWithRootViewController:importViewController];
        
        [fileViewController release];
        [importViewController release];

        [navControllerFile.navigationBar setTintColor:[UIColor colorWithRed:.19 green:.19 blue:0.19 alpha:1]]; 
        [navControllerImpo.navigationBar setTintColor:[UIColor colorWithRed:.19 green:.19 blue:0.19 alpha:1]]; 
                
		UITabBarController *myTabBarController = [[UITabBarController alloc]init];
		
        NSArray *controllersArray=[NSArray arrayWithObjects: navControllerFile,navControllerImpo,filterViewController,viewerViewController,otherViewController,otherViewController1,otherViewController2,otherViewController3, nil];
		
        [filterViewController release];
        [viewerViewController release];
        [otherViewController release];
        [otherViewController1 release];
        [otherViewController2 release];
        [otherViewController3 release];

        [myTabBarController setViewControllers: controllersArray];
        
		//Change active View
		[self presentModalViewController:myTabBarController animated:YES];
		
        [myTabBarController release];
        
	}
	//if connection resul are not "OK"
	else
    {
        
		NSString *errorString =NSLocalizedString(@"dati_errati",@"");
		UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:errorString 
																 delegate:nil 
														cancelButtonTitle:@"OK" 
												   destructiveButtonTitle:nil 
														otherButtonTitles:nil]; 
		[actionSheet showInView:[[self view] window]];
		[actionSheet release]; 
		
	}
   
}


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

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //Dismiss keyboard when tap on view
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    gestureRecognizer.delegate=self;
    [self.tableView addGestureRecognizer:gestureRecognizer];
    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIControl class]]) {
        // we touched a button, slider, or other UIControl
        return NO; // ignore the touch
    }
    return YES; // handle the touch
}

- (void) hideKeyboard {

    [usernameField resignFirstResponder];
    [passwordField resignFirstResponder];
}



#pragma mark -
#pragma mark Table view data source


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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    // Return the number of rows in the section.
    return [elements count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
   	[cell.contentView addSubview: [elements objectAtIndex:[indexPath row]]];
	
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;

    UIImageView *logoImage=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
    [logoImage setFrame:CGRectMake(screenSize.width/2-100,10,200,40)];

    // create the parent view that will hold header Label
	UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, screenSize.width, 50)];
	
	    
    [customView addSubview:logoImage];

	return customView;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 80;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    
    
    //Login button
    UIButton *loginButton =[UIButton buttonWithType:UIButtonTypeCustom];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"login.png"] forState:UIControlStateNormal];
    [loginButton setFrame:CGRectMake(screenSize.width/2-93, 32, 186, 32)];
    [loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *logoImage=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"inaf.png"]];
    [logoImage setFrame:CGRectMake(screenSize.width/2-75,150,150,100)]; 
    
    // create the parent view that will hold header Label
	UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0, screenSize.width, 350)];
	
    
    [customView addSubview:loginButton];
    [customView addSubview:logoImage];
	return customView;

    
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
 	return 150;
}

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
