//
//  LoginViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 14-6-20.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "LoginViewController.h"

#import "RetrievePassViewController.h"
#import "UILabel+FontAppearance.h"
#import "OLDataProvider.h"
#import "NotificationNameCenter.h"
#import "OfflineSettingViewController.h"
#import "MainViewController.h"
#import "WebViewController.h"

@interface LoginViewController ()
@property (strong, nonatomic) IBOutlet UIButton *requestLoginBtn;

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
#ifdef BUILD_HMLG
    self.title=@"HMLG";
    self.checkOfflineMode.hidden=true;
#endif
#ifdef BUILD_NPD
    self.title=@"NPD";
    self.checkOfflineMode.hidden=false;
#endif
    self.showList = false;
    
    
    self.bb_close.image=[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic];
    
    [self.checkSavePassword setImage:[UIImage imageNamed:@"checkbox"] forState:UIControlStateNormal];
    [self.checkSavePassword setImage:[UIImage imageNamed:@"checkbox_check"] forState:UIControlStateSelected];
    
    
    
    [self.checkOfflineMode setImage:[UIImage imageNamed:@"checkbox"] forState:UIControlStateNormal];
    [self.checkOfflineMode setImage:[UIImage imageNamed:@"checkbox_check"] forState:UIControlStateSelected];
    
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString * user = [AESCrypt decrypt:[defaults stringForKey:@"user"] password:@"usai"];
    
    
    NSString * password = [AESCrypt decrypt:[defaults stringForKey:@"password"] password:@"usai"];
    
    if(user.length>0&&password.length>0)
    {
        self.edituser.text=user;
        self.editpass.text=password;
        self.checkSavePassword.selected=true;
        
    }
    //   NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    //    [defaults removeObjectForKey:@"EnableOfflineMode"];
    //    [defaults setBool:self.checkOfflineMode.selected forKey:@"EnableOfflineMode"];
    self.checkOfflineMode.selected=[defaults boolForKey:@"EnableOfflineMode"];
    
    [self.checkOfflineMode addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.checkSavePassword addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
    self.checkOfflineMode.tag=999;
    
    self.logindata = [iSalesDB get_saveduser];
    
    
    
    UIButton* combobutton=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
    [combobutton setBackgroundImage:[UIImage imageNamed:@"combo_24"] forState:UIControlStateNormal];
    [combobutton addTarget:self action:@selector(LoginList:) forControlEvents:UIControlEventTouchUpInside];
    
    self.edituser.rightView = combobutton;
    self.edituser.rightViewMode=UITextFieldViewModeAlways;
    
    
    
    self.Loginlist.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.Loginlist.layer.borderWidth = 1.0;
    //  self.Loginlist.layer.cornerRadius=15;
    self.Loginlist.layer.masksToBounds=true;
    // Do any additional setup after loading the view.
}
- (void)LoginList:(UIButton *)sender {
    [self.edituser endEditing:true];
    self.showList= !self.showList;
    self.Loginlist.hidden = !self.showList;
    //    showList;
}
-(void)checkboxClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    
    if(btn.tag==999)
    {
        
        bool haveofflineData=[OLDataProvider check_offlinedata];
        
        if(btn.selected)
        {
            if(haveofflineData)
            {
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                
                bool forcedownload = [defaults boolForKey:@"Forcedownload"];
                
                if(forcedownload)
                {
                    btn.selected = !btn.selected;
                    
                    [RAUtils alert_view:@"Detected incomplete sync, please finish sync first." title:@"Incomplete sync"];
                }
                else
                {
                    [defaults removeObjectForKey:@"EnableOfflineMode"];
                    [defaults setBool:self.checkOfflineMode.selected forKey:@"EnableOfflineMode"];
                    
                    [defaults synchronize];
                    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                    appDelegate.offline_mode = self.checkOfflineMode.selected;
                }

            }
            else
            {
                btn.selected = !btn.selected;
                
                [RAUtils alert_view:@"Offline data not found, you must login online and download offline data first." title:@"Offline data not found"];
            }
        }
        else
        {
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            [defaults removeObjectForKey:@"EnableOfflineMode"];
            [defaults setBool:self.checkOfflineMode.selected forKey:@"EnableOfflineMode"];
            
            [defaults synchronize];
            AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            appDelegate.offline_mode = self.checkOfflineMode.selected;
        }
        
        
    }
    else
    {
        if(!btn.selected)
        {
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            [defaults removeObjectForKey:@"user"];
            [defaults removeObjectForKey:@"password"];
            [defaults synchronize];
            
            
            NSString* encryptu=[AESCrypt encrypt:self.edituser.text password:@"usai"];
            
            NSString* sql=[NSString stringWithFormat:@"delete from login_info where name='%@'",encryptu];
            [iSalesDB execSql:sql];
            self.logindata = [iSalesDB get_saveduser];
            [self.Loginlist reloadData];
        }
        
    }
}
- (IBAction)CloseClick:(id)sender {
    
    [self dismissViewControllerAnimated:true completion:nil];
    if(self.returnValue)
        self.returnValue(false);
    
    
    
}
- (IBAction)onRetrievePassword:(id)sender {
    RetrievePassViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:@"RetrievePassViewController" ];
    //            dvc
    //    UINavigationController* nv = self.navigationController;
    
    [self.navigationController pushViewController:vc animated:true];
}
- (IBAction)onLoginClick:(UIButton *)sender {
    NSString* user = self.edituser.text;
    NSString* password = self.editpass.text;
    
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    
    bool forcedownload = [defaults boolForKey:@"Forcedownload"];
    
    if(forcedownload && self.checkOfflineMode.selected)
    {
        self.checkOfflineMode.selected = !self.checkOfflineMode.selected;
        
        [RAUtils alert_view:@"Detected incomplete sync, please finish sync first." title:@"Incomplete sync"];
        return;
    }
    
    if(user.length==0||password.length==0)
    {
        //        UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @"Error!" message:@"user or password can not be empty." 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];
        //
        //
        //        //[[UILabel appearanceWhenContainedIn:UIAlertView.class, nil] setAppearanceFont:[UIFont boldSystemFontOfSize:10]];
        //        [alert show];
        
        
        [RAUtils alert_view:@"Username or Password cannot be blank." title:@"Cannot sign-in"];
        return;
    }
    DebugLog(@"Login...   user= %@ ; password= %@",user,password);
    
    
    
    
    self.btnLogin.enabled = false;
    UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Sign in"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        int ret=[iSalesNetwork  Authorize:user password:password];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
            self.btnLogin.enabled = true;
            
            if(ret==RESULT_TRUE)
                
            {
               
                //
                //                NSString* contactid=[self.content_data[indexPath.row] valueForKey:@"contact_id"] ;
                AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                //                appDelegate.contact_id=contactid;
                //                appDelegate.contact_name =[self.content_data[indexPath.row] valueForKey:@"name"];
                
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                [defaults removeObjectForKey:@"user"];
                [defaults removeObjectForKey:@"password"];
                NSString* encryptu=[AESCrypt encrypt:appDelegate.user password:@"usai"];
                NSString* encryptp=[AESCrypt encrypt:self.editpass.text password:@"usai"] ;
                if(self.checkSavePassword.selected)
                {
                    
                    [defaults setValue:encryptu forKey:@"user"];
                    [defaults setValue:encryptp forKey:@"password"];
                    sqlite3 *db = [iSalesDB get_db];
                    
                    int count =[iSalesDB get_recordcount:db table:@"login_info" where:[NSString stringWithFormat:@"name='%@'",encryptu]];
                    
                    if(count==0)
                    {
                        
                        NSString * savelogin=[NSString stringWithFormat:@"insert into login_info(name,pwd) values('%@','%@')",encryptu,encryptp];
                        [iSalesDB execSql:savelogin db:db];
                    }
                    else
                    {
                        NSString * savelogin=[NSString stringWithFormat:@"update login_info set pwd='%@' where name='%@'",encryptp,encryptu];
                        [iSalesDB execSql:savelogin db:db];
                    }
                    
                    [iSalesDB close_db:db];
                    
                    //                    [defaults setBool:TRUE forKey:@"autologin"];
                }
                else
                {
                    NSString* sql=[NSString stringWithFormat:@"delete from login_info where name='%@'",encryptu];
                    [iSalesDB execSql:sql];
                }
                [defaults synchronize];
                
                [self dismissViewControllerAnimated:YES completion:^{
                    
                    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                    
                    bool offline_dirty=[defaults boolForKey:@"OFFLINE_DIRTY"];
                    sqlite3* db = [iSalesDB get_db];
                    int offline_user_exist=[iSalesDB get_recordcount:db table:@"offline_login" where:[NSString stringWithFormat:@"username='%@'",appDelegate.user ]];
                    
                    [iSalesDB close_db:db];
                    
                    
                    
                    if(offline_dirty&& !appDelegate.offline_mode&& offline_user_exist>0)
                    {
                        
                        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Detected new offline data" message:@"Do you want to sync with server?" preferredStyle:UIAlertControllerStyleAlert];
                        //block代码块取代了delegate
                        
                        
                        UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes(Recommended)" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                            
                            
                            
                            
                            UIApplication * app = [UIApplication sharedApplication];
                            AppDelegate *appDelegate = (AppDelegate *)[app delegate];
                            //UIViewController* active_vc = appDelegate.active_controller;
                            OfflineSettingViewController * offlineVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"OfflineSettingViewController"];
                            //    loginvc.delegate = self;
                            //    loginvc.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态，自己看看是哪种
                            //       appDelegate.active_controller = gunVC;
                            //        gunVC.onDismissVC = ^(){
                            //            appDelegate.active_controller = active_vc;
                            //        };
                            UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:offlineVC] ;
                            
                            
                            
                            
                            
                            //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
                            
                            navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
                            [appDelegate.main_vc presentViewController:navi animated:YES completion:^{
                                
                                
                                    MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
                                
                                [main_vc checklogin:true];
                                //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
                                
                                DebugLog(@"about present.........");
                                
                                //   self.btop = false;
                                //  <#code#>
                            }];
                            
                            
                            
                            
                        }];
                        
                        UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                            
                            if(self.returnValue)
                                self.returnValue(true);
                            [[NSNotificationCenter defaultCenter] postNotificationName:LoginOK_HandleUrgencyFile_Notification object:nil];
                            
                        }];
                        
                        [alertControl addAction:actionTwo];
                        [alertControl addAction:alertthree];
                        
                        
                        
                        [appDelegate.main_vc presentViewController:alertControl animated:YES completion:nil];
                        
                        
                        
                        
                    }
                    else
                    {
                    if(self.returnValue)
                        self.returnValue(true);
                    [[NSNotificationCenter defaultCenter] postNotificationName:LoginOK_HandleUrgencyFile_Notification object:nil];
                    }
                        }];


                
                //                if (self.delegate && [self.delegate respondsToSelector:@selector(LoginViewControllerDidLogin:)]) {
                //                    [self.delegate LoginViewControllerDidLogin:self];
                //                }
                
                [[NSNotificationCenter defaultCenter] postNotificationName:User_LoginOK_Notification object:nil];
            }
            else
            {
                NSString* msg=nil;
                
                switch (ret) {
                        
                    case RESULT_NET_NOTAVAILABLE:
                        msg = MSG_NET_NOTAVAILABLE;
                        break;
                        
                        
                    case RESULT_NET_ERROR:
                        msg = MSG_NET_ERROR;
                        break;
                        
                        
                    case RESULT_FALSE:
                        msg = MSG_USERAUTH_ERROR;
                        break;
                        
                    case RESULT_VER_LOW:
                        msg = MSG_VER_LOW;
                        break;
                        
                    case RESULT_LOGIN_DEVICE:
                        msg= MSG_LOGIN_DEVICE;
                        break;
                    default:
                        break;
                }
                
                [RAUtils alert_view:msg title:@"Cannot sign-in"];
                
                
                
            }
            
            
        });
    });
    
    
    
}

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

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    return 44;
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.logindata.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSMutableDictionary* up = self.logindata[indexPath.row];
    
    
    
    NSString *CellIdentifier = @"LoginListCell";
    UITableViewCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString* name=up[@"name"];
    cell.textLabel.text = name;
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSMutableDictionary* up = self.logindata[indexPath.row];
    self.edituser.text = up[@"name"];
    self.editpass.text = up[@"pwd"];
    
    self.showList=false;
    self.Loginlist.hidden=true;
    self.checkSavePassword.selected=true;
    
}
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//    
//    return true;
//}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    self.showList=false;
    self.Loginlist.hidden=true;
    
}

#pragma mark - action

- (IBAction)requestLoginBtnClicked:(UIButton *)sender {
    
    WebViewController *webVC = [self.storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
    webVC.url = URL_REQUEST_LOGIN;
    webVC.title = @"Request Login";
    webVC.backItemDismiss = YES;
    
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:webVC];
    nav.modalPresentationStyle = UIModalPresentationFormSheet;
    
    [self presentViewController:nav animated:YES completion:nil];
    
}



@end
