//
//  DocumentPageViewController.m
//  AntsContract
//
//  Created by Ray on 12/16/16.
//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
//

#import "DocumentPageViewController.h"
#import "PageViewController.h"
#import "SignatureListViewController.h"
#import "SignatureViewController.h"
#import "PDFUtils.h"
#import "ACNetwork.h"

#import "AFHTTPSessionManager.h"
#import "AppDelegate.h"
#import "ACNetwork.h"
#import "RAUtils.h"
#import "PDFViewController.h"
#import "config.h"
#import "AESCrypt.h"
#import "CustomIOSAlertView.h"

#import "ImageUtils.h"


@interface DocumentPageViewController ()

@end

@implementation DocumentPageViewController

-(NSMutableDictionary*) templateInit:(NSMutableDictionary*) template
{
    
    
    NSString* temp = NSTemporaryDirectory();
    NSString* filename =[NSString stringWithFormat:@"%@.png", [[NSUUID UUID] UUIDString]];
    NSString* qrpath=[temp stringByAppendingPathComponent:filename];
    UIImage* qrimg=[RAUtils generateBarCode:self.docment_id width:200 height:44];//[QRCodeGenerator qrImageForString:order_code imageSize:240];
    bool bwrite=[UIImagePNGRepresentation(qrimg)writeToFile: qrpath    atomically:YES];
    
    
    
    for(int i=0;i<[template[@"count"] intValue];i++)
    {
        NSMutableDictionary* page =template[[NSString stringWithFormat:@"page_%d",i]];
        for(int j=0;j<[page[@"count"] intValue];j++)
        {
            NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
            NSString* type = control[@"type"];
            NSString* field =control[@"field"];
            if([type isEqualToString:@"Label"])
            {
                if([field isEqualToString:@"doc_number"])
                {
                    control[@"value"]= self.docment_id;
                }
            }
            else if([type isEqualToString:@"Image"])
            {
                NSString* name =control[@"name"];
                if([name isEqualToString:@"BarCode"])
                {
                    control[@"value"]= qrpath;
                }
            }
        }
    }
    return template;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //    self.delegate = self;
    //    self.dataSource = self;
    
    
    self.signatureData= [[NSMutableDictionary alloc] init];
    
    
    self.document = [PDFUtils OpenPDF:self.pdfName];
    self.total_page = CGPDFDocumentGetNumberOfPages (self.document);
    self.controlTemplate = [self templateInit:[PDFUtils loadControl:self.templateName]];
    
    
    PageViewController* startingViewController=[self viewControllerAtIndex:0];
    
    // NSArray* viewControllers =[NSArray arrayWithObjects:page_0,nil];
    
    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.pageViewController.delegate = self;
    
    //    PageViewController *startingViewController = [self viewControllerAtIndex:0 storyboard:self.storyboard];
    NSArray *viewControllers = @[startingViewController];
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    
    self.pageViewController.dataSource = self;
    
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    
    // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
    CGRect pageViewRect = self.view.bounds;
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        pageViewRect = pageViewRect;//CGRectInset(pageViewRect, 40.0, 40.0);
    }
    self.pageViewController.view.frame = pageViewRect;
    
    [self.pageViewController didMoveToParentViewController:self];
    
    // Do any additional setup after loading the view.
}
-(void) dealloc
{
    CFBridgingRelease(self.document);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)onSignatureClicked:(id)sender {
    
    //    CGRect cellrect_screen = [RAUtils relativeFrameForScreenWithView:trigger];
    //
    //
    //    CGRect rect1=[self.view convertRect:cellrect_screen fromView:[[[UIApplication sharedApplication] delegate] window]];
    //
    //    DebugLog(@"convert1 %@",NSStringFromCGRect(rect1));
    SignatureListViewController *signatureVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureListViewController"];
    signatureVC.title=@"Signatures";
    signatureVC.signatureData = self.signatureData;
    
    
    signatureVC.blk_Add = ^()
    {
        
        __block UIImage* signimg=nil;
        SignatureViewController * vc =[ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureViewController"];
        
        vc.onReturnImg = ^(UIImage* img)
        {
            
            
            signimg = img;
            
            if(signimg!=nil)
                [PDFUtils addSignature:signimg to:self.signatureData];
                //[self addSignature:signimg];
                
            
            
        };
        
        //    orderinfoVC.url_type = URL_REMOTE;
        //    orderinfoVC.request_url=URL_CARTDELIVERY;
        //
        //    orderinfoVC.params = params;
        //
        //    orderinfoVC.delegate=self;
        //
        //    if(checked.count==count)
        //    {
        //    orderinfoVC.have_tail = true
        //    }
        
        [self.navigationController pushViewController:vc animated:true];
        
        
        
    };
    
    signatureVC.blk_Fill =^(NSString* file)
    {
        
        
        
        //            NSString* file_name=[file lastPathComponent];
//        
//        NSData* img_data=[ImageUtils load_img:file];
//        
//        if(img_data!=nil)
//        {
//            
//            UIImage* image=[UIImage imageWithData:img_data];
//            touchImageView.image = image;
//            
//            long index = touchImageView.tag - CONTROL_BASE;
//            self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
//            
//        }
        
    };
    
    UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:signatureVC];
    navi.modalPresentationStyle=UIModalPresentationPopover;
    
    UIPopoverPresentationController* popPc = navi.popoverPresentationController;
    popPc.permittedArrowDirections = UIPopoverArrowDirectionUp;
    popPc.barButtonItem = sender;
    popPc.delegate = nil;
    
    
    
    [self presentViewController:navi animated:true completion:nil];
    
    ////    menu.selector = self.selector;
    ////
    ////    menu.selectordelegate = self;
    //
    //    // 1.创建一个UIPopover
    //    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]];
    //
    //
    //
    //    UIPopoverPresentationController
    //    // 2.设置尺寸
    //    //    popover.popoverContentSize = CGSizeMake(320, 44 * 5);
    //
    //    // 3.从哪里显示出来 --> 指向item
    //
    //    [popover presentPopoverFromRect:self.view.frame   inView:self.view permittedArrowDirections:0 animated:YES];
    //    //  [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    //
    ////    self.popover = popover;
    //    popover pop
    //
    // [self performSegueWithIdentifier:@"selector_popover" sender:self];
    
}
- (IBAction)onSaveClicked:(id)sender {
    
    if([self verifyData]==false)
        return;
    
    
    __weak typeof(self) weakSelf = self;
    NSString* pdffile = [PDFUtils SavePDF:self.controlTemplate source:self.document window_rect:CGRectMake(0, 0, 768, 960)];
    
    
    NSString* zipfile=[ACNetwork prepareUploadFile:pdffile json:self.controlTemplate];
    
  //  return;
    
    {
        
        
        UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
        

//        self.uploadProgress.progress = 0;
        
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        

        {
            
            //    UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            //    [waitalert show];
            
//            NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
            
            AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
            
            
            
            NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
            
//            if(appDelegate.user!=nil)
//                [params setValue:appDelegate.user forKey:@"user"];
//            //    if(appDelegate.contact_id!=nil)
//            //        [params setValue:appDelegate.contact_id forKey:@"contactId"];
//            if(appDelegate.password!=nil)
//                [params setValue:appDelegate.password forKey:@"password"];
            
            
            [params setValue:[AESCrypt AES128Encrypt:appDelegate.user  key:@"usai2010"] forKey:@"user"];
            [params setValue:[AESCrypt AES128Encrypt:appDelegate.password  key:@"usai2010"] forKey:@"password"];
            
            [params setValue:@"deviceMain" forKey:@"_operate"];
            
            
            UIDevice * dev = [UIDevice currentDevice];
            NSUUID* uuid =dev.identifierForVendor;
#if TARGET_IPHONE_SIMULATOR//模拟器
            [params setValue:@"simulator_uuid" forKey:@"deviceid"];
#elif TARGET_OS_IPHONE//真机
            [params setValue:uuid.UUIDString forKey:@"deviceid"];
#endif

            
            
            NSMutableString *body=[[NSMutableString alloc]init];
            //参数的集合的所有key的集合
            NSArray *keys= [params allKeys];
            DebugLog(@"================parms==================");
            //遍历keys
            for(int i=0;i<[keys count];i++)
            {
                //得到当前key
                NSString *key=[keys objectAtIndex:i];
                //如果key不是pic，说明value是字符类型，比如name：Boris
                if(![key isEqualToString:@"pic"])
                {
//                    //添加分界线，换行
//                    [body appendFormat:@"%@\r\n",MPboundary];
                    //添加字段名称，换2行
                    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
                    //添加字段的值
                    [body appendFormat:@"%@\r\n",[params objectForKey:key]];
                    DebugLog(@"parameter: key=%@   value=%@",key,[params objectForKey:key]);
                }
            }
            DebugLog(@"================parms==================");
            
            NSData* data = [NSData dataWithContentsOfFile: zipfile];
            
            NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_PDF parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                [formData appendPartWithFileData:data name:@"upfile" fileName:[zipfile lastPathComponent] mimeType:@"application/zip"];
            } error:nil];
            
            
            //        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //            [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
            //        } error:nil];
            //
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            
            
            
            //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
            
            //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
            
            //
            NSProgress *progress = nil;
            
            NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                
                //        [progress removeObserver:self forKeyPath:@"fractionCompleted"];
                
                
                 [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                
                if (error) {
                    
                    NSString* err_msg = [error localizedDescription];
                    DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
                    
                    
                    NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                    
                    DebugLog(@"data string: %@",str);
                    [RAUtils message_alert:@"Can not connect to server please try again." title:@"Save document" controller:self] ;
                    
                } else {
                    DebugLog(@"response ");
                    
                    
                    
                    NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
                    
                    // 再将NSData转为字符串
                    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    
                    //            NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                    
                    DebugLog(@"data string: %@",jsonStr);
                    
                    NSDictionary* json = responseObject;
                    
                    
                    
                    
                    if([[json valueForKey:@"result"] intValue]==2)
                    {

                        [weakSelf.navigationController popToRootViewControllerAnimated:false];
//
//                        
                        if(weakSelf.OnSave)
                            weakSelf.OnSave(pdffile);

                        
                    }
                    else
                    {
                        [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save document" controller:self] ;
                    }
                    
                    
                }
                //  [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
            }];
            
            
            
            
          //  [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
            //
            
            
            
            
            
            
            [uploadTask resume];
            
        }
    }
    
  //  [PDFUtils savep
}


-(void) addSignature :(UIImage*) img to:(NSMutableDictionary*)signatureData
{
    
    
    if(true)
    {
        NSString* newfile=[self saveTempSignature:UIImagePNGRepresentation(img)];
        
        int newidx = [self.signatureData[@"count"] intValue];
        
       // [@"file"]= newfile;
        
        NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
        item[@"file"]=newfile;
        signatureData[[NSString stringWithFormat:@"item_%d",newidx]] = item;
        signatureData[@"count"]=[NSNumber numberWithInt:newidx+1];
        
        
    
    }
    
    
    
}
-(NSString *) saveTempSignature:(NSData *) image
{
    NSString* tempDir = NSTemporaryDirectory();
    
    NSString *saveFileName=[NSString stringWithFormat:@"%@.png",[[NSUUID UUID ] UUIDString] ] ;
    
    NSString *newFilePath=[tempDir stringByAppendingPathComponent:saveFileName];
    
    
       bool bsuccess=[image writeToFile:newFilePath atomically:YES];
    if(bsuccess)
    {

        return newFilePath;
    }
    else
    {
        return nil;
    }

}
/*
 #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.
 }
 */


- (PageViewController *)viewControllerAtIndex:(NSUInteger)index
{
    //Return the PDFViewController for the given index.
    if ((self.total_page == 0 )|| (index > self.total_page) ) {
        return nil;
    }
    
    //Create a new view controller and pass suitable data.
    PageViewController *PageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
    
    PageViewController.pageRef =  CGPDFDocumentGetPage (self.document , index+1);
    PageViewController.pageIndex = index;
    
    ;
    PageViewController.controlTemplate = self.controlTemplate[[NSString stringWithFormat:@"page_%lu",(unsigned long)index]];
    
    PageViewController.signatureData = self.signatureData;
    //PageViewController.pdfview = [self.pagePDF objectAtIndex:index];
    
    /*
     PageViewController.pdfview = [[PDFView alloc]initWithFrame:self.view.frame atPage:index];
     [PageViewController.view addSubview:PageViewController.pdfview];
     NSLog(@"index = %d",index);
     
     
     */
    return PageViewController;
}

- (NSUInteger) indexOfViewController:(PageViewController *)viewController
{
    return viewController.pageIndex;//[self.pagePDF indexOfObject:viewController.pdfview];
}

#pragma mark verify data
- (UIView *)createDemoView:(NSString*) msg
{
    UIView *demoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 200)];
    
    //    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 270, 180)];
    //    [imageView setImage:[UIImage imageNamed:@"demo"]];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 270, 10)];
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.text=@"Please complete missing fields:";
    titleLabel.numberOfLines = 0;
    titleLabel.lineBreakMode =NSLineBreakByWordWrapping;
    //    titleLabel.textAlignment = NSTextAlignmentRight;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    CGSize constraintkey = CGSizeMake(270, 20000.0f);//key label width is 40% cell width;
    CGSize sizetitle = [@"Please complete missing fields:" sizeWithFont:[UIFont systemFontOfSize:20.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
    
    //[titleLabel sizeToFit];
    //    titleLabel.center.x = demoView.center.x;
    titleLabel.frame = CGRectMake(10, 10, 270, sizetitle.height);
    [demoView addSubview:titleLabel];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, 10)];
    lineLabel.font = [UIFont boldSystemFontOfSize:17];
    lineLabel.text=msg;
    lineLabel.numberOfLines = 0;
    lineLabel.lineBreakMode =NSLineBreakByWordWrapping;
    
    CGSize sizemsg = [msg sizeWithFont:[UIFont boldSystemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
    
    lineLabel.frame = CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, sizemsg.height);
    //[lineLabel sizeToFit];
    
    [demoView addSubview:lineLabel];
    demoView.frame = CGRectMake(0, 0, 290, lineLabel.frame.origin.y+lineLabel.frame.size.height+25);
    return demoView;
}
-(bool) verifyData
{
    return true;
    bool ret=true;
    int more=0;
    NSMutableArray* fields=[[NSMutableArray alloc] init];
    
    for(int i=0;i<[self.controlTemplate[@"count"] intValue];i++)
    {
        NSMutableDictionary* page =self.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
        for(int j=0;j<[page[@"count"] intValue];j++)
        {
            NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
            NSString* type = control[@"type"];
            NSString* name = control[@"aname"];
            bool required = [control[@"required"] boolValue];
            
            if(required==false)
                continue;
            if([type isEqualToString:@"Check"])
            {
                NSArray* arr = control[@"value"];
                if(arr.count==0)
                {
                    ret=false;
                    
                    NSString* msg=[NSString stringWithFormat:@"%u Page %d %@ is missing.",fields.count+1,i+1,name];
                    if(fields.count<15)
                        [fields addObject:msg];
                    else
                        more++;
                }
                
            }
            else if(/*[type isEqualToString:@"Signature"]||*/[type isEqualToString:@"Image"]||[type isEqualToString:@"Label"])
            {
                continue;
            }
            else
            {
                NSString* str = control[@"value"];
                if(str.length==0)
                {
                    ret=false;
                    NSString* msg=[NSString stringWithFormat:@"%u Page %d %@ is missing.",fields.count+1,i+1,name];
                    if(fields.count<15)
                        [fields addObject:msg];
                    else
                        more++;
                }
            }
        }
    }
    if(ret==false)
    {
        if(more>0)
        {
            NSString* msg=[NSString stringWithFormat:@"And %d more missing field.",more];
            [fields addObject:@"......"];
                [fields addObject:msg];
        }
        NSString* missfields=[fields componentsJoinedByString:@"\n"];
        NSString* msg = [NSString stringWithFormat:@"%@",missfields];
        
        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
        
        
        
        
        // Add some custom content to the alert view
        [alertView setContainerView:[self createDemoView:msg]];
        
        // Modify the parameters
        
        
        
        [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"OK", nil]];
        //[alertView setDelegate:self];
        
        // You may use a Block, rather than a delegate.
        [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
            //   DebugLog(@"Block: Button at position %d is clicked on alertView %d.", buttonIndex, (int)[alertView tag]);
            [alertView close];
        }];
        
        //  [alertView setUseMotionEffects:true];
        
        // And launch the dialog
        
        [alertView sizeToFit];
        [alertView show];
        
        
    }
    return ret;
}

#pragma mark - Page View Controller Data Source


- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
    if ((index == 0 ) || (index == NSNotFound)){
        return nil;
    }
    
    index--;
    return  [self viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
    if (index == NSNotFound)
    {
        return nil;
    }
    
    index++;
    
    if (index == self.total_page){
        return  nil;
    }
    
    return [self viewControllerAtIndex:index];
}


#pragma mark - UIPageViewController delegate methods
- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
    if (true||UIInterfaceOrientationIsPortrait(orientation) || ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)) {
        // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
        
        UIViewController *currentViewController = self.pageViewController.viewControllers[0];
        NSArray *viewControllers = @[currentViewController];
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
        
        self.pageViewController.doubleSided = NO;
        return UIPageViewControllerSpineLocationMin;
    }
    
//    // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
//    PageViewController *currentViewController = self.pageViewController.viewControllers[0];
//    NSArray *viewControllers = nil;
//    
//    NSUInteger indexOfCurrentViewController = [self indexOfViewController:currentViewController];
//    if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) {
//        UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
//        viewControllers = @[currentViewController, nextViewController];
//    } else {
//        UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
//        viewControllers = @[previousViewController, currentViewController];
//    }
//    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
//    
//    
//    return UIPageViewControllerSpineLocationMid;
}



@end
