//
//  ApexMobileFirstViewController.m
//  Apex Mobile
//
//  Created by Ray on 14-2-24.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//
 
#import "ApexMobileFirstViewController.h"
#import "FunctionSelectViewController.h"
@interface ApexMobileFirstViewController ()

//－（void）Authorize : (NSString*) user :(NSString*) password;
//-(void)Authorize : (NSString*) user password:(NSString*) password;


@end



@implementation ApexMobileFirstViewController

- (IBAction)RetrieveButtonClick:(UIButton *)sender {
    [self performSegueWithIdentifier:@"RETRIEVE" sender:self];
}


- (IBAction)LoginButtonClick:(UIButton *)sender {
    
    
    
    NSString*password= self.editPassword.text;
    NSString*user = self.editUser.text;
    if(user.length==0||password.length==0)
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"alert_title_error", nil) message:NSLocalizedString(@"alert_msg_upcanotempty", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil];
        //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
        [alert show];
        return;
    }
     DebugLog(@"Login...   user= %@ ; password= %@",self.editUser.text,self.editPassword.text);
    
    
    self.loginButton.enabled = false;
    self.mum.hidden=false;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        int ret=[ApexMobileNetwork Authorize:self.editUser.text password:self.editPassword.text];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.mum.hidden=true;
            self.loginButton.enabled = true;
            
            if (ret==RESULT_TRUE)
            {
                
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                [defaults removeObjectForKey:@"user"];
                [defaults removeObjectForKey:@"password"];
//                if(self.checkSavePassword.selected)
                {
                    
                    
                    [defaults setValue:[AESCrypt encrypt:self.editUser.text password:@"usai"] forKey:@"user"];
                    [defaults setValue:[AESCrypt encrypt:self.editPassword.text password:@"usai"] forKey:@"password"];
                    [defaults setBool:TRUE forKey:@"autologin"];
                }
                [defaults synchronize];
                [self dismissViewControllerAnimated:true completion:^{
                    ;
                }];

//                [self performSegueWithIdentifier:@"LOGIN" sender:self];
                
                
            }
            else
            {
//                int a = RESULT_NET_NOTAVAILABLE;
                NSString* message = nil;
                switch (ret) {
                    case RESULT_NET_NOTAVAILABLE:
                        message = NSLocalizedString(@"net_not_available", nil);
                        break;
                    case RESULT_NET_ERROR:
                        message = NSLocalizedString(@"net_error", nil);
                        break;
                    case RESULT_FALSE:
                        message = NSLocalizedString(@"auth_error", nil);
                        break;
                    case RESULT_VER_LOW:
                        message = NSLocalizedString(@"ver_low", nil);
                        break;
                        
                    default:
                        message=[NSString stringWithFormat:@"Failed to login code %d",ret];
                        break;
                }
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"alert_title_error", nil) message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil];
                [alert show];
            }
 
            

        });
    });
    
    
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self view] endEditing:YES];
}

-(void)checkboxClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
}
//- (IBAction)onRetrievePassword:(UIButton *)sender {
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.checkSavePassword setImage:[UIImage imageNamed:@"unchecked_32.png"] forState:UIControlStateNormal];
    [self.checkSavePassword setImage:[UIImage imageNamed:@"checked_32.png"] forState:UIControlStateSelected];
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString * user = [AESCrypt decrypt:[defaults stringForKey:@"user"] password:@"usai"];
    
    self.editUser.delegate = self;
    self.editPassword.delegate = self;
    self.resize = false;
    self.ioffset = 0;
    NSString * password = [AESCrypt decrypt:[defaults stringForKey:@"password"] password:@"usai"];
    
    if(user.length>0&&password.length>0)
    {
        self.editUser.text=user;
        self.editPassword.text=password;
        self.checkSavePassword.selected=true;
        
    }
    
    
    [self.checkSavePassword addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:checkSavePassword];
	// Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}
-(void) textFieldDidBeginEditing:(UITextField *)textField
{
//    CGRect textFrame =  self.loginButton.frame;
    int loginpos = self.loginButton.frame.origin.y+self.loginButton.frame.size.height;
    self.ioffset = 216 -(self.view.frame.size.height-loginpos);
    if(self.ioffset>0)
    {
        self.resize = true;
        NSTimeInterval animationDuration = 0.30f;
        CGRect frame = self.view.frame;
        frame.origin.y -=self.ioffset;//view的Y轴上移
        frame.size.height +=self.ioffset; //View的高度增加
        self.view.frame = frame;
        [UIView beginAnimations:@"ResizeView" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];//设置调整界面的动画效果
    }
}

/**
 结束编辑UITextField的方法，让原来的界面还原高度
 */
-(void) textFieldDidEndEditing:(UITextField *)textField
{
//    if(prewTag == -1) //当编辑的View不是需要移动的View
//    {
//        return;
//    }
//    float moveY ;
    
    if(self.resize)
    {
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
//    if(prewTag == textField.tag) //当结束编辑的View的TAG是上次的就移动
//    {   //还原界面
//        moveY =  prewMoveY;
        frame.origin.y +=self.ioffset;
        frame.size. height -=self.ioffset;
        self.view.frame = frame;
//    }
    //self.view移回原位置
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
    [textField resignFirstResponder];
        self.ioffset=0;
    }
    
}
@end
