//
//  ViewController.m
//  iDing
//
//  Created by MacBook Pro on 28/01/13.
//  Copyright (c) 2013 Abusamy Ltd.. All rights reserved.
//

#import "ViewController.h"
#import "iDingSettings.h"
#import "MFSideMenu.h"
#import "AppDelegate.h"

@implementation ViewController

@synthesize passwordTxtFld,userNameTxtFld,mutableData,urlConnection;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self)
    {
        self.title = @"auto i login";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    userNameTxtFld.delegate = self;
    passwordTxtFld.delegate = self;
    [createAccountBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
     
    if (isForiPad)
    {
       // [loginCustomView setFrame:LOGIN_CUSTOM_FRAME_iPad];
    }else{
        [loginCustomView setFrame:LOGIN_CUSTOM_FRAME];
        [createAccountBtn setFrame:CNA_BTN_FRAME];
        [lineLbl setFrame:CNA_LINE_FRAME];

    }
    
    userNameTxtFld.text = [UIAPPDELEGATE loggedUserName];// @"whiletrue@hotmail.com";// @"test@test.com";
    passwordTxtFld.text =[UIAPPDELEGATE loggedPassword];//@"1";

   // userNameTxtFld.text = @"alex@gpspos.info";
//    userNameTxtFld.text = @"whiletrue@hotmail.com";// @"test@test.com";
//    passwordTxtFld.text = @"1";
  //  userNameTxtFld.text = @"alex@alex.com";// @"test@test.com";
  //  passwordTxtFld.text = @"password";
   // NSLog(@"UIAPPDELEGATE.dToken 2=%@" , UIAPPDELEGATE.dToken);
    if(UIAPPDELEGATE.isAutoLogin)
    {
        NSLog(@"Trying to auto login");
      
             
        if([[UIAPPDELEGATE loggedUserName] length]>0)
            [self performSelector:@selector(autoLoginWork) withObject:nil afterDelay:0.1];
    }
}


-(BOOL)isVisible
{
    UIViewController* topMostController = self.navigationController.visibleViewController;
    // NSString* topMostControllerName = [NSString stringWithFormat:@"%s", class_getName([topMostController class])];
    // myNSLog2( @"Visible Controller is %@", topMostControllerName);
    // if([topMostControllerName isEqualToString:@"MainMenuViewController"])
    
    if([topMostController isKindOfClass:[ViewController class]])
    {
        //is topmost visible view controller
        return TRUE;
    }
    
    return false;
}

-(void)viewWillAppear:(BOOL)animated
{
    userNameTxtFld.text = [UIAPPDELEGATE loggedUserName];// @"whiletrue@hotmail.com";// @"test@test.com";
    passwordTxtFld.text =[UIAPPDELEGATE loggedPassword];//@"1";

    [super viewWillAppear:YES];
}

#pragma Textfield Delegates

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if(textField == self.userNameTxtFld)
    {
        [self.passwordTxtFld becomeFirstResponder];
    }
    else
    {
        [textField resignFirstResponder];
        return YES;
    }
    
    
    return NO;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    NSLog(@"dealloc11");

    [self.passwordTxtFld release];
    [self.userNameTxtFld release];
    [loginBtn release];
    [createAccountBtn release];
    [super dealloc];
}

-(BOOL)isInternetAvailable
{
    BOOL isAvailable;
    Reachability* reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if(remoteHostStatus == NotReachable)
    {
        isAvailable = FALSE;
    }
    else if (remoteHostStatus == ReachableViaWiFi)
    {
        isAvailable = TRUE;
    }
    else if (remoteHostStatus == ReachableViaWWAN)
    {
        isAvailable = TRUE;
    }
    return isAvailable;
}

- (IBAction)loginAction:(id)sender
{
    [self loginWork];
}

- (void)autoLoginWork
{
   if([self isVisible])
       [self loginWork];
}

- (IBAction)loginWork
{

    //NSLog(@"Login");
    BOOL isInternetAvailable = [self isInternetAvailable];
    
    if(isInternetAvailable == TRUE)
    {
        
        if([self.userNameTxtFld.text length] > 0 && [self.passwordTxtFld.text length] > 0)
        {
            isLogin = TRUE;
            [self login:self.userNameTxtFld.text password:self.passwordTxtFld.text];
        }
        else
        {
            isLogin = FALSE;
           /* UIAlertView *detailsAlert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter all the details" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [detailsAlert show];
            [detailsAlert release];*/
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            // Configure for text only and offset down
            hud.mode = MBProgressHUDModeText;
            if([self.userNameTxtFld.text length] <1 )
                hud.labelText = @"Please enter a valid username!";
            else if([self.passwordTxtFld.text length] <1 )
                hud.labelText = @"Please enter a valid password!";
            else
                hud.labelText = @"Please enter valid information!";
            
            hud.margin = 10.f;
            hud.yOffset = 150.f;
            hud.removeFromSuperViewOnHide = YES;
            
            [hud hide:YES afterDelay:3];
        }

    }
    else
    {
        isLogin = FALSE;
        UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Connection Alert" message:@"Please check internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];
        
       /* NoConnectionView *ncv = [[NoConnectionView alloc]initWithFrame:CGRectMake(0, 0, 150, 100)];
        ncv.center = self.view.center;
        [self.view addSubview:ncv];*/
        //[self.view makeToast:@"No Internet Connection" duration:2 position:@"bottom" image:[UIImage imageNamed:@"No_Net@2x.png"]];
    }
}

-(void)login:(NSString *)userName password:(NSString *)password
{
    // http://mocal.mobi/verifyUsername.php?username=XXX&password=YYY&deviceid=UUID.
    
   // NSString *loginUrl = @"http://mocal.mobi/verifyUsername.php?username=%@&password=%@&deviceid=%@";
    
    if(self.mutableData !=nil)
    {
        self.mutableData = nil;
    }
    self.mutableData = [NSMutableData data];
   // NSLog(@"UIAPPDELEGATE.dToken=%@" , UIAPPDELEGATE.dToken);
    
  NSString *deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
                        
                        //uniqueIdentifier];
    
    NSString *loginUrl = [NSString stringWithFormat:@"http://www.theautoi.com/verifyUsername.php?username=%@&password=%@&token=%@&deviceid=%@&cams=%d",userName,password,UIAPPDELEGATE.dToken,deviceId,UIAPPDELEGATE.isFourcams?4:1];
    NSLog(@"Verify username: %@", loginUrl);
    NSURL *url = [NSURL URLWithString:loginUrl];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    NSLog(@"loginUrl=%@" , loginUrl);
    
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    [self.urlConnection setAccessibilityHint:@"Login"];
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
    
}

- (IBAction)createAccountAction:(id)sender
{
   // NSLog(@"Create");
    isLogin = FALSE;
    BOOL isInternetAvailable = [self isInternetAvailable];
    if(isInternetAvailable == TRUE)
    {
        NewAccountViewController *navc = [[NewAccountViewController alloc]initWithNibName:isForiPad?@"NewAccViewCntrlr_iPad": @"NewAccountViewController" bundle:nil];
        [self.navigationController pushViewController:navc animated:YES];
    }
    else
    {
        UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Connection Alert" message:@"Please check internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];

    }
}

#pragma mark NSURLConnection Delegates
#pragma mark Connection callbacks

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //
	[self.mutableData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[self.mutableData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    NSString *response = [[NSString alloc]initWithData:self.mutableData encoding:NSASCIIStringEncoding];
   // NSLog(@"the response is %@",response);
    //if([connection.accessibilityHint isEqualToString:@"Login"])
    if(isLogin == TRUE)
    {
        [self parseLoginResponse:response];
    }
}

-(void)parseLoginResponse:(NSString *)response
{
    
    //NSLog(@"the response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        UIAPPDELEGATE.loggedUserName = [self.userNameTxtFld text];
        UIAPPDELEGATE.loggedPassword = [self.passwordTxtFld text];
        [UIAPPDELEGATE saveSettings];
    }
    else if([response rangeOfString:@"error"].location != NSNotFound)
    {
       UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No account available with given details" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];
    
        return;
    }
    else
    {
        UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Connection issue!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];
        
        return;
    }

    
    MainMenuViewController *mnVw = [[MainMenuViewController alloc]initWithNibName:@"MainMenuViewController" bundle:nil];
    [self.navigationController pushViewController:mnVw animated:YES];
}

@end
