//
//  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"

@interface DocumentPageViewController ()

@end

@implementation DocumentPageViewController

- (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 = [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)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];
        
        
        
    };
    
    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 {
    [PDFUtils SavePDF:self.controlTemplate source:self.document window_rect:CGRectMake(0, 0, 768, 960)];
  //  [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 - 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
