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

#import "PDFUtils.h"
#import "PDFPage.h"
#import "ImageDrawable.h"
#import "TextDrawable.h"
#import "RectDrawable.h"


@implementation PDFUtils
+(NSString*) addSignature :(UIImage*) img to:(NSMutableDictionary*)signatureData
{
    
    
    if(true)
    {
        NSString* newfile=[self saveTempSignature:UIImagePNGRepresentation(img)];
        
        int newidx = [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];
        
        return newfile;
        
    }
    
    
    
}
+(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;
    }
    
}
+(NSMutableDictionary*) loadControl:(NSString*)templateName
{
    NSString *path = [[NSBundle mainBundle] pathForResource:templateName ofType:nil];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSMutableDictionary *ret = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] mutableCopy];
    return ret;
}
+(CGPDFDocumentRef)OpenPDF:(NSString*) file
{
    //获取路径
    /*
     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//坐标
     
     NSString *saveDirectory=[paths objectAtIndex:0];
     
     NSString *saveFileName=@"myPDF.pdf";
     
     NSString *newFilePath=[saveDirectory stringByAppendingPathComponent:saveFileName];
     */
    
    NSString *default_path = [[NSBundle mainBundle] pathForResource:file ofType:nil];
    const char *filename=[default_path UTF8String];
    
    NSLog(@"%@",default_path);
    
    //关联上下文的对象
    
    //   CGContextRef pdfContext;
    
    CFStringRef path;
    
    CFURLRef url;
    
    path=CFStringCreateWithCString(NULL, filename, kCFStringEncodingUTF8);
    
    url=CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
    
    
    CFRelease(path);
    CGPDFDocumentRef document;
    document = CGPDFDocumentCreateWithURL (url);
    CFRelease(url);
    size_t totalpage = CGPDFDocumentGetNumberOfPages (document);
    
    if (totalpage == 0) {
        printf("[%s] needs at least one page!\n", [@"myPDF.pdf" UTF8String] );
        return NULL;
    } else {
        printf("[%ld] pages loaded in this PDF!\n", totalpage);
        
        
        /*8
         for (NSInteger pageNumber = 1; pageNumber <= count; pageNumber++)
         {
         CGPDFPageRef pageRef = CGPDFDocumentGetPage(document, pageNumber);
         
         CGPDFDictionaryRef pageDictionaryFromPage = CGPDFPageGetDictionary(pageRef);
         
         if (pageDictionaryFromPage == pageDictionaryFromDestArray) // Found it
         {
         targetPageNumber = pageNumber; break;
         }
         
         
         }*/
    }
    
    //    CGPDFPageRef page= CGPDFDocumentGetPage(document, 0);
    //    CGContextDrawPDFPage(<#CGContextRef  _Nullable c#>, <#CGPDFPageRef  _Nullable page#>)
    
    return document;
    
    
    
}
+(CGRect)WindowRect2PDFRect:(CGRect)rect pdf_rect:(CGRect)pdf_rect window_size:(CGSize)window_size
{
    CGRect pdf_expand;
    float offset_x = 0;
    float offset_y = 0;
    float scale =1;
    if(pdf_rect.size.height>=pdf_rect.size.width)
    {
        pdf_expand = CGRectMake(0, 0, pdf_rect.size.height*window_size.width/window_size.height, pdf_rect.size.height);
        offset_x = (pdf_expand.size.width-pdf_rect.size.width)/2;
        scale = pdf_rect.size.height/window_size.height;
        
    }
    else
    {
        pdf_expand = CGRectMake(0, 0, pdf_rect.size.width, pdf_rect.size.width*window_size.height/window_size.width);
        offset_y = (pdf_expand.size.height-pdf_rect.size.height)/2;
        scale = pdf_rect.size.width/window_size.width;
    }
    float x=rect.origin.x*scale-offset_x;
    float y=rect.origin.y*scale-offset_y;
    float width = rect.size.width*scale;
    float height = rect.size.height*scale;
    
    return CGRectMake(x, y, width, height);
    
}

+(NSString*)SavePDF:(NSMutableDictionary*) controlTemplate source:(CGPDFDocumentRef )document window_rect:(CGRect)window_rect
{
    
    //获取路径
    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//坐标
    
    NSString *saveDirectory=[paths objectAtIndex:0];
    
    NSString *saveFileName=[NSString stringWithFormat:@"%@.pdf",[[NSUUID UUID ] UUIDString] ] ;;
    
    NSString *newFilePath=[saveDirectory stringByAppendingPathComponent:saveFileName];
    
    const char *filename=[newFilePath UTF8String];
    
    NSLog(@"%@",newFilePath);
    //设置页面大小 Letter纸
    
    //CGPDFDocumentGetMediaBox(document,1);
    CGPDFDictionaryRef pdf_dict= CGPDFDocumentGetInfo(document);
    
    

    
    
    //关联上下文的对象
    
    
    
    CFStringRef path;
    
    CFURLRef url;
    
    path=CFStringCreateWithCString(NULL, filename, kCFStringEncodingUTF8);
    
    url=CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
    
    CFBridgingRelease(path);
    // CGPDFCONTEXTCREATE
    
  
    CGContextRef pdfContext;
    CGRect docsize = CGRectMake(0, 0, 100, 100);
    pdfContext=CGPDFContextCreateWithURL(url, &docsize, nil);
    size_t page_count=CGPDFDocumentGetNumberOfPages(document);
    for(int i=1;i<=page_count;i++)
    {
        NSMutableDictionary* page_control=controlTemplate[[NSString stringWithFormat:@"page_%d",i-1]];
        CGPDFPageRef page= CGPDFDocumentGetPage (document , i);
        
        CGRect papersize=CGPDFPageGetBoxRect(page, kCGPDFMediaBox);

        
        
        CGContextBeginPage(pdfContext, &papersize);
        
        PDFPage* pdfPage = [[PDFPage alloc] init:nil size:papersize];
        
        [pdfPage DirectDraw:pdfContext page:page];
        
        
        for(int j=0;j<[page_control[@"count"] intValue];j++)
        {
            NSMutableDictionary* control=page_control[[NSString stringWithFormat:@"control_%d",j]];
            
            PDFDrawable * control_drawable = nil;
            CGRect control_rect = CGRectMake([control[@"pos_x"] floatValue], [control[@"pos_y"] floatValue], [control[@"width"] floatValue], [control[@"height"] floatValue]);
            

            NSString* control_type = control[@"type"];
            if([control_type isEqualToString:@"Signature"])
            {
                NSString* value = control[@"value"];
                if(value.length==0)
                    continue;
                
                
                control_drawable=[[ImageDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"local" source:value hAlign:@"center" vAlign:@"middle"];
            }
            else if([control_type isEqualToString:@"TextView"])
            {
                NSString* value = control[@"value"];
                if(value.length==0)
                    continue;
                NSString* size = control[@"size"];
                if(size.length==0)
                    size=@"10";
                
                control_drawable=[[TextDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"const" source:value textAlignment:@"center" vAlign:@"middle" size:size];
            }
            else if([control_type isEqualToString:@"Check"])
            {
                NSArray* value = control[@"value"];
                if(value.count==0)
                    continue;
                NSArray* cadedate = control[@"cadedate"];
                float marker_size = [control[@"marker_size"] floatValue];
    
                for(int c=0;c<value.count;c++)
                {
                    NSArray* marker=cadedate[[value[c] intValue]];
                    CGRect marker_rect= CGRectMake([marker[1][0] floatValue] ,[marker[1][1] floatValue], marker_size, marker_size);
                    PDFDrawable * marker_drawable = [[RectDrawable alloc] init:[self WindowRect2PDFRect:marker_rect pdf_rect:papersize window_size:window_rect.size] color:@"0x000000"];
                    if(marker_drawable)
                        [pdfPage DirectDraw:pdfContext drawable:marker_drawable];
                }
                
//                NSString* size = control[@"size"];
//                if(size.length==0)
//                    size=@"10";
//                
//                control_drawable=[[TextDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"const" source:value textAlignment:@"center" vAlign:@"middle" size:size];
            }
            if(control_drawable)
                [pdfPage DirectDraw:pdfContext drawable:control_drawable];
            
            
            
        }
//        NSMutableDictionary* tline1= [LineDrawable createlineTemplate:1 from:CGPointMake(20, 20) to:CGPointMake(500,500)];
//        LineDrawable* line1=nil;
//        line1= [[LineDrawable alloc] init:tline1];
//        
//        [pdfPage DirectDraw:pdfContext drawable:line1];
//                NSRange range = NSMakeRange(0,9999);
//        [line1 Draw:pdfContext dataSource:nil ParentRect:papersize startX:0 startY:0 flipHeight:0 range:range];
        
         CGContextEndPage(pdfContext);

       // [pdfPage Draw:pdfContext dataSource:nil];
//        [self drawPage:pdfContext template:page size:papersize dataSource:data];
        
        
//        CFBridgingRelease(page);
    }
    CGContextRelease(pdfContext);
    CFBridgingRelease(url);
//    //开始画pdf
//    
//    //    NSString *temtext=[[NSString alloc]init];
//    //
//    //    const char *text=(char *)[temtext UTF8String];
//    //
//    //    int  width;
//    //
//    //    int height;
//    //
//    
//    //    [self newpage:pdfContext size:papersize];
//    
//    
//    
//    CGContextRelease(pdfContext);
    
    return newFilePath;
    
}

@end
