//
//  OfflineSettingViewController.m
//  iSales-NPD
//
//  Created by Ray on 5/11/16.
//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
//

#import "OfflineSettingViewController.h"
#import "iSalesNetwork.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "OLDataProvider.h"
#import "OfflineUnlockViewController.h"
//#import "SyncControlPanelViewController.h"

@interface OfflineSettingViewController ()

@end

@implementation OfflineSettingViewController
- (IBAction)onUnlockClicked:(id)sender {
    
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Unlock offline" message:@"Unlock offline to sync with another account." preferredStyle:UIAlertControllerStyleAlert];
    //block代码块取代了delegate
    
    
    
    UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Unlock" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

        sqlite3* db = [iSalesDB get_db];
        int offline_user_iscurrent=[iSalesDB get_recordcount:db table:@"offline_login" where:[NSString stringWithFormat:@"username='%@'",appDelegate.user ]];
        
        [iSalesDB close_db:db];
        
        
        if(offline_user_iscurrent>0)
        {
        self.bunlock=true;
        }
        else
        {
            OfflineUnlockViewController * unlockvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"OfflineUnlockViewController"];
            unlockvc.returnValue = ^(bool blogin){
                self.bunlock=true;
            };
            UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:unlockvc] ;
            
            
            
            
            
            //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
            
            navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
            [self presentViewController:navi animated:YES completion:^{
                
                //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
                
                DebugLog(@"LoginViewController present.........");
                
                //   self.btop = false;
                //  <#code#>
            }];

            
            
        }
        
        
        
        
//        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Are you sure remove all models from cart?" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        //block代码块取代了delegate
//        
//        
//        
//        UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
//            UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Remove Models From Cart"];
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                
//                NSDictionary* cart_json = [iSalesNetwork cart_remove:ids];
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    
//                    [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
//                    
//                    if([[cart_json valueForKey:@"result"] intValue]==2)
//                    {
//                        
//                        [self end_edit];
//                        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//                        [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:true];
//                        [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:true];
//                    }
//                    else
//                    {
//                        [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Delete Model" controller:self] ;
//                    }
//                    
//                    
//                    
//                });
//            });
//            
//            
//        }];
//        
//        UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//            DebugLog(@"No");
//        }];
//        [alertControl addAction:actionOne];
//        
//        [alertControl addAction:alertthree];
//        
//        //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
//        
//        
//        [self presentViewController:alertControl animated:YES completion:nil];
//        
//        DebugLog(@"%@",self.edit_select_arr);
//        
//        
    }];
 
    
    UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        DebugLog(@"No");
    }];
    [alertControl addAction:actionOne];
     [alertControl addAction:alertthree];
    
    
    //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
    
    
    [self presentViewController:alertControl animated:YES completion:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.bunlock=false;
    // Do any additional setup after loading the view.
    
    
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    bool  offline = [defaults boolForKey:@"EnableOfflineMode"] ;
    
    NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
    NSString*  lastsync = [defaults stringForKey:@"LastSync"] ;
    if(lastsync!=nil)
        self.label_sync.text = lastsync;
    
    if(ver==nil)
        self.label_ver.text=@"No offline data";
    else
        self.label_ver.text=ver;
    self.switch_offline.on = offline;
    
    
    
    self.edgesForExtendedLayout = UIRectEdgeNone ;
    
    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector( onCloseClick:)];
    self.navigationItem.rightBarButtonItem = closeButton;
    
    
    
    
}
- (IBAction)OnCheckUpdate:(id)sender {
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    
    
    if(appDelegate.bLogin==false)
    {
        
        LoginViewController * loginvc =[ [UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"];
        loginvc.returnValue = ^(bool blogin){
            
            
            if(blogin)
            {
                if(appDelegate.user_type==USER_ROLE_EMPLOYEE)
                {
                    
                    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                    
                    
                    NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
                    
                    if(sender==nil)
                    {
                        [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn parentvc:self];
//                        SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
//                        syncVC.action_string=@"Download";
//                        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
//                        
//                        
//                        
//                        
//                        
//                        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
//                        
//                        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
//                        [self presentViewController:navi animated:YES completion:^{
//                            
//                            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
//                            
//                            DebugLog(@"about present.........");
//                            
//                            //   self.btop = false;
//                            //  <#code#>
//                        }];
                    }
                    else
                    {
                        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Check offline update?" message:@"Please connect to WIFI network and plug charging cable, KEEP SCREEN ON AND KEEP APP RUNNING FOREGROUND, download data will take a while." preferredStyle:UIAlertControllerStyleAlert];
                        //block代码块取代了delegate
                        
                        
                        UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                            [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn parentvc:self];
                            
                            
//                            SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
//                            syncVC.action_string=@"Download";
//                            UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
//                            
//                            
//                            
//                            
//                            
//                            //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
//                            
//                            navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
//                            [self presentViewController:navi animated:YES completion:^{
//                                
//                                //        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) {
                        }];
                        
                        [alertControl addAction:actionTwo];
                        [alertControl addAction:alertthree];
                        
                        
                        
                        [self presentViewController:alertControl animated:YES completion:nil];
                    }

                    
                    
                }
                else
                {
                    
                }
            }
            else
            {
                [RAUtils alert_view:@"Must login" title:@"Data sync"];
            }
            
            
            
        };
        
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
        
        
        
        
        
        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
        
        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
        [self presentViewController:navi animated:YES completion:^{
            
            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
            
            DebugLog(@"LoginViewController present.........");
            
            //   self.btop = false;
            //  <#code#>
        }];
    }
    else
    {
        
        
       // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        sqlite3* db = [iSalesDB get_db];
        int offline_user_iscurrent=[iSalesDB get_recordcount:db table:@"offline_login" where:[NSString stringWithFormat:@"username='%@'",appDelegate.user ]];
        
        [iSalesDB close_db:db];
        

        
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        
        NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
        
        
        if(offline_user_iscurrent==0 && ver!=nil)
        {
            if(!self.bunlock)
            {
            [RAUtils alert_view:@"Current login account is different from the offline account, to continue with sync, all current offline data will be erased, you must unlock offline lock first. " title:@"Sync denied."];
            return;
            }
            else
            {
                ver=nil;
            }
        }
        
        if(sender==nil)
        {
            [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn parentvc:self];
//            SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
//            syncVC.action_string=@"Download";
//            UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
//            
//            
//            
//            
//            
//            //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
//            
//            navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
//            [self presentViewController:navi animated:YES completion:^{
//                
//                //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
//                
//                DebugLog(@"about present.........");
//                
//                //   self.btop = false;
//                //  <#code#>
//            }];
        }
        else
        {
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Check offline update?" message:@"Please connect to WIFI network and plug charging cable, KEEP SCREEN ON AND KEEP APP RUNNING FOREGROUND, download data will take a while." preferredStyle:UIAlertControllerStyleAlert];
            //block代码块取代了delegate
            
            
            UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn parentvc:self];
                
                

                
                
            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            }];
            
            [alertControl addAction:actionTwo];
            [alertControl addAction:alertthree];
            
            
            
            [self presentViewController:alertControl animated:YES completion:nil];
        }

        
        
        
    }
    
    
    
    
    
    
    
    
    
}

- (void)onCloseClick:(UIButton *)sender {
    
    //    if(self.onDismissVC)
    //        self.onDismissVC();
    [self dismissViewControllerAnimated:true completion:nil];
}

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

    
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    

    
    
    
    
    
    
    if(self.switch_offline.isOn==false)
    {
        //disable offline
        
        
        if(appDelegate.bLogin)
        {
            UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Sign out"];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                NSDictionary* return_json = [iSalesNetwork logout];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                    
                    
                    if([[return_json valueForKey:@"result"] intValue]==2)
                    {

                        [appDelegate Logout];
                        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                        [defaults removeObjectForKey:@"EnableOfflineMode"];
                        [defaults setBool:self.switch_offline.isOn forKey:@"EnableOfflineMode"];
                        
                        [defaults synchronize];
                        appDelegate.offline_mode =self.switch_offline.isOn;
                        
                        [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadContact:true immediately:false];
                        [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
                        
                        
                        [((MainViewController*)appDelegate.main_vc) switchToHome];
                    }
                    else
                    {
                       // [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Sign Out" controller:self] ;
                    }
                    
                    
                    
                    
                });
            });
        }
        else
        {
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            [defaults removeObjectForKey:@"EnableOfflineMode"];
            [defaults setBool:self.switch_offline.isOn forKey:@"EnableOfflineMode"];
            
            [defaults synchronize];
            appDelegate.offline_mode =self.switch_offline.isOn;
            
            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadContact:true immediately:false];
            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
            
            
            [((MainViewController*)appDelegate.main_vc) switchToHome];
        }
    }
    else
    {
        bool haveofflineData=[OLDataProvider check_offlinedata];
        if(haveofflineData)
        {
            // have offline data
            if(appDelegate.bLogin)
            {
                UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Sign out"];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* return_json = [iSalesNetwork logout];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                        
                        
                        if([[return_json valueForKey:@"result"] intValue]==2)
                        {
                            
                            [appDelegate Logout];
                            
                            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                            [defaults removeObjectForKey:@"EnableOfflineMode"];
                            [defaults setBool:self.switch_offline.isOn forKey:@"EnableOfflineMode"];
                            
                            [defaults synchronize];
                            appDelegate.offline_mode =self.switch_offline.isOn;
                            
                            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadContact:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
                            
                            
                            [((MainViewController*)appDelegate.main_vc) switchToHome];
                        }
                        else
                        {
                            // [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Sign Out" controller:self] ;
                        }
                        
                        
                        
                        
                    });
                });
            }
        }
        else
        {
            //no offline data download form server first.
            // restore switch state.
            
            [self.switch_offline setOn:!self.switch_offline.isOn];
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Offline data not found, download it from server?" message:@"Please connect to WIFI network and plug charging cable, KEEP SCREEN ON AND KEEP APP RUNNING FOREGROUND, download data will take a while." preferredStyle:UIAlertControllerStyleAlert];
            //block代码块取代了delegate
            
            
            UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                [self OnCheckUpdate:nil];
                
                
            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                //                [self.switch_offline setOn:false];
                //[RAUtils message_alert:@"No item in the cart" title:@"Offline" controller:self] ;
            }];
            
            [alertControl addAction:actionTwo];
            [alertControl addAction:alertthree];
            
            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
            
            
            [self presentViewController:alertControl animated:YES completion:nil];
        }
        
        //
        //        UIApplication * app = [UIApplication sharedApplication];
        //        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        //
        //        NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
        //        //
        //        //        [appDelegate check_offline:ver];
        //        //        return;
        //
        //        //        if(ver.length==0)
        //        {
        //
        //            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Check offline update?" message:nil preferredStyle:UIAlertControllerStyleAlert];
        //            //block代码块取代了delegate
        //
        //
        //            UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //                //   UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Checking offline data"];
        //                //init offline mode
        //                //                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //                //
        //                //
        //                //                  //  [self check_offline];
        //                //                });
        //                [appDelegate check_offline:ver];
        //
        //
        //
        //            }];
        //
        //            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        //                //                [self.switch_offline setOn:false];
        //                //[RAUtils message_alert:@"No item in the cart" title:@"Offline" controller:self] ;
        //            }];
        //
        //            [alertControl addAction:actionTwo];
        //            [alertControl addAction:alertthree];
        //
        //            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
        //
        //
        //            [self presentViewController:alertControl animated:YES completion:nil];
        //
        //
        //
        //
        //
        //
        //
        //
        //        }
        //        else
        //        {
        //
        //        }
    }
}

-(void) download_file:(NSString*)url type:(NSString*)type
{
    
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
