//
//  TableDrawable.m
//  pdftest
//
//  Created by Ray on 10/18/16.
//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
//

#import "TableDrawable.h"
#import "GroupDrawable.h"
#import "LineDrawable.h"


@implementation TableDrawable
-(void) setDrawableTemplate:(NSMutableDictionary *)drawableTemplate
{
    
    [super setDrawableTemplate:drawableTemplate];
    
    

    
    
    //    kCTTextAlignmentJustified CT_ENUM_AVAILABLE(10_8, 6_0) = 3,
    //    kCTTextAlignmentNatural   CT_ENUM_AVAILABLE(10_8, 6_0) = 4,
    
    
    //    _drawableTemplate = drawableTemplate;
    //    self.margin_left=[self.drawableTemplate[@"margin_left"] doubleValue];
    //    self.margin_right=[self.drawableTemplate[@"margin_right"] doubleValue];
    //    self.margin_top=[self.drawableTemplate[@"margin_top"] doubleValue];
    //    self.margin_bottom=[self.drawableTemplate[@"margin_bottom"] doubleValue];
    //    self.rect = CGRectMake(0, 0, [self.drawableTemplate[@"width"] doubleValue], [self.drawableTemplate[@"height"] doubleValue]);
}
-(CGRect) Query_Rect:(CGContextRef) context dataSource:(NSMutableDictionary*)data ParentRect:(CGRect)p_rect startX:(double) x startY:(double) y flipHeight:(double)flip_height range:(NSRange)between_header_and_footer
{
    /*
    bool header_repeat = [self.drawableTemplate[@"header_repeat"] boolValue];
    bool drawheader = true;
    
    
    NSMutableDictionary* table_data = data[self.drawableTemplate[@"data_source"]];
    
    NSMutableDictionary* rows = self.drawableTemplate[@"rows"];
    int count = [rows[@"count"] intValue];
    
*/
    
    
    CGRect pdfrect =  [self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    CGRect parentrect =[self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
/*
    
    float dy=y;
    
    
    
    dy= [self QueryHeader:context dataSource:data ParentRect:p_rect startX:x startY:y flipHeight:flip_height range:between_header_and_footer dy:dy];

    for(int i=0;i<count;i++)
        
    {
        NSMutableDictionary * rowjson =rows[ [NSString stringWithFormat:@"row_%d",i ] ];
        PDFDrawable* drawable_obj= [[GroupDrawable alloc] init:rowjson];
        drawable_obj.delegate = self.delegate;
        NSMutableDictionary* rows_data = table_data[rowjson[@"data_source"]];
        int row_data_count=[rows_data[@"count"] intValue];
        
        int j=0;
        while(true)
            //        for(int j=0;j<row_data_count;j++)
        {
            
            if(i!=count-1&& j==row_data_count)
                break;
            
            if(drawheader)
            {
                
                drawheader = false;
            }
            
            NSMutableDictionary * row_data =rows_data[ [NSString stringWithFormat:@"item_%d",j ] ];
            CGRect row_rect= [drawable_obj Query_Rect:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];

            
            if(row_rect.size.width>parentrect.size.width||row_rect.size.height>parentrect.size.height)
            {
                // cell 比 table 还要大，模板有错，直接返回。
                return parentrect;
            }
            
            if(dy+row_rect.size.height> between_header_and_footer.location+between_header_and_footer.length )
            {
                if(j<row_data_count)
                {
                    //越界，新起一页
                    if (self.delegate && [self.delegate respondsToSelector:@selector(outofPage:)]) {
                        [self.delegate outofPage:context];
                        dy=y;
                        if(header_repeat)
                        {
                            dy= [self QueryHeader:context dataSource:data ParentRect:p_rect startX:x startY:y flipHeight:flip_height range:between_header_and_footer dy:dy];
                            
                            //                            drawheader=true;
                        }
                        //  dx=0;
                    }
                }
                else
                {
                    break;
                    //    goto finish_draw;
                }
                
                
            }
            
            [drawable_obj Draw:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
            //            if([direction isEqualToString:@"H"])
            //            {
            //                dx+=row_rect.size.width;
            //                if(dx+row_rect.size.width>parentrect.size.width)
            {
                //                    dx=0;
                dy+=row_rect.size.height;
            }
            
            //            }
            j++;
        }
        
    }
    //finish_draw:*/
   // [self DrawBound:context dataSource:data ParentRect:p_rect startX:x startY:y flipHeight:flip_height range:between_header_and_footer];
    return parentrect;
}
-(float) QueryHeader:(CGContextRef) context dataSource:(NSMutableDictionary*)data ParentRect:(CGRect)p_rect startX:(double) x startY:(double) y flipHeight:(double)flip_height range:(NSRange)between_header_and_footer dy:(double) dy
{
    // draw table header
    
    NSMutableDictionary* table_data = data[self.drawableTemplate[@"data_source"]];
    
    NSMutableDictionary* rows = self.drawableTemplate[@"rows"];
    //   int count = [rows[@"count"] intValue];
    
    //    CGRect pdfrect = /*CGRectMake(self.rect.origin.x+self.margin_left+p_rect.origin.x, self.rect.origin.y+self.margin_top+p_rect.origin.y, self.rect.size.width-self.margin_right, self.rect.size.height-self.margin_bottom);//*/[self to_pdf_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    
    
    CGRect pdfrect =  [self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    CGRect parentrect =[self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    NSMutableDictionary * headerjson =rows[@"header"];
    PDFDrawable* header_drawable_obj= [[GroupDrawable alloc] init:headerjson];
    header_drawable_obj.delegate = self.delegate;
    NSMutableDictionary* header_data = table_data[headerjson[@"data_source"]];
    //    int row_data_count=[header_data[@"count"] intValue];
    NSMutableDictionary * row_data =header_data[ [NSString stringWithFormat:@"item_%d",0 ] ];
    CGRect row_rect= [header_drawable_obj Query_Rect:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
    if(row_rect.size.width>parentrect.size.width||row_rect.size.height>parentrect.size.height)
    {
        // cell 比 table 还要大，模板有错，直接返回。
        return 0;
    }
    
    if(dy+row_rect.size.height> between_header_and_footer.location+between_header_and_footer.length )
    {
        //越界，新起一页
        if (self.delegate && [self.delegate respondsToSelector:@selector(outofPage:)]) {
            [self.delegate outofPage:context];
            dy=y;
            //  dx=0;
        }
    }
    
  //  [header_drawable_obj Draw:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
    //            if([direction isEqualToString:@"H"])
    //            {
    //                dx+=row_rect.size.width;
    //                if(dx+row_rect.size.width>parentrect.size.width)
    {
        //                    dx=0;
        dy+=row_rect.size.height;
    }
    return dy;
}
-(float) DrawHeader:(CGContextRef) context dataSource:(NSMutableDictionary*)data ParentRect:(CGRect)p_rect startX:(double) x startY:(double) y flipHeight:(double)flip_height range:(NSRange)between_header_and_footer dy:(double) dy
{
    // draw table header
    
    NSMutableDictionary* table_data = data[self.drawableTemplate[@"data_source"]];
    
    NSMutableDictionary* rows = self.drawableTemplate[@"rows"];
 //   int count = [rows[@"count"] intValue];
    
    //    CGRect pdfrect = /*CGRectMake(self.rect.origin.x+self.margin_left+p_rect.origin.x, self.rect.origin.y+self.margin_top+p_rect.origin.y, self.rect.size.width-self.margin_right, self.rect.size.height-self.margin_bottom);//*/[self to_pdf_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    
    
    CGRect pdfrect =  [self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    CGRect parentrect =[self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    NSMutableDictionary * headerjson =rows[@"header"];
    PDFDrawable* header_drawable_obj= [[GroupDrawable alloc] init:headerjson];
    header_drawable_obj.delegate = self.delegate;
    NSMutableDictionary* header_data = table_data[headerjson[@"data_source"]];
    //    int row_data_count=[header_data[@"count"] intValue];
    NSMutableDictionary * row_data =header_data[ [NSString stringWithFormat:@"item_%d",0 ] ];
    CGRect row_rect= [header_drawable_obj Query_Rect:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
    if(row_rect.size.width>parentrect.size.width||row_rect.size.height>parentrect.size.height)
    {
        // cell 比 table 还要大，模板有错，直接返回。
        return 0;
    }
    
    if(dy+row_rect.size.height> between_header_and_footer.location+between_header_and_footer.length )
    {
        //越界，新起一页
        if (self.delegate && [self.delegate respondsToSelector:@selector(outofPage:)]) {
            [self.delegate outofPage:context];
            dy=y;
            //  dx=0;
        }
    }
    
    [header_drawable_obj Draw:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
    //            if([direction isEqualToString:@"H"])
    //            {
    //                dx+=row_rect.size.width;
    //                if(dx+row_rect.size.width>parentrect.size.width)
    {
        //                    dx=0;
        dy+=row_rect.size.height;
    }
    return dy;
}
-(CGRect) Draw:(CGContextRef) context dataSource:(NSMutableDictionary*)data ParentRect:(CGRect)p_rect startX:(double) x startY:(double) y flipHeight:(double)flip_height range:(NSRange)between_header_and_footer
{
    
    
    bool header_repeat = [self.drawableTemplate[@"header_repeat"] boolValue];
    bool drawheader = true;
    NSMutableDictionary* table_data = data[self.drawableTemplate[@"data_source"]];

    NSMutableDictionary* rows = self.drawableTemplate[@"rows"];
    int count = [rows[@"count"] intValue];
    
    //    CGRect pdfrect = /*CGRectMake(self.rect.origin.x+self.margin_left+p_rect.origin.x, self.rect.origin.y+self.margin_top+p_rect.origin.y, self.rect.size.width-self.margin_right, self.rect.size.height-self.margin_bottom);//*/[self to_pdf_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    
    
    CGRect pdfrect =  [self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    CGRect parentrect =[self to_parent_rect:p_rect pos:self.rect offsetX:0 offsetY:0];
    float dy=y;
    

    
                    dy= [self DrawHeader:context dataSource:data ParentRect:p_rect startX:x startY:y flipHeight:flip_height range:between_header_and_footer dy:dy];
    //            }
    
//    int i=0;
    for(int i=0;i<count;i++)
    
    {
        NSMutableDictionary * rowjson =rows[ [NSString stringWithFormat:@"row_%d",i ] ];

        
        
        if(rowjson[@"separator"]!=nil)
        {
        PDFDrawable* separator_obj= [[LineDrawable alloc] init:rowjson[@"separator"]];
        separator_obj.delegate = self.delegate;
        [separator_obj Draw:context dataSource:nil ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
        }
        NSMutableDictionary* rows_data = table_data[rowjson[@"data_source"]];
        int row_data_count=[rows_data[@"count"] intValue];
        
        int j=0;
        while(true)
//        for(int j=0;j<row_data_count;j++)
        {
            PDFDrawable* drawable_obj= [[GroupDrawable alloc] init:rowjson];
            drawable_obj.delegate = self.delegate;
            if(i!=count-1&& j==row_data_count)
                break;

            if(drawheader)
            {

                drawheader = false;
            }
          
            NSMutableDictionary * row_data =rows_data[ [NSString stringWithFormat:@"item_%d",j ] ];
            CGRect row_rect= [drawable_obj Query_Rect:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
     /*   
            if(dy+row_rect.size.height> between_header_and_footer.location+between_header_and_footer.length)
            {
                //越界，新起一页
                if (self.delegate && [self.delegate respondsToSelector:@selector(outofPage:)]) {
                    [self.delegate outofPage:context];
                    dy=0;
                }
            }
             [drawable_obj Draw:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
            dy+=row_rect.size.height;
//            pos = CGPointMake(0, rowpos.y+pos.y);
           
           */
            
            if(row_rect.size.width>parentrect.size.width||row_rect.size.height>parentrect.size.height)
            {
                // cell 比 table 还要大，模板有错，直接返回。
                return parentrect;
            }

            
            if([self.drawableTemplate[@"split"] boolValue])
            {
                if(/*dy+row_rect.size.height+self.margin_top+self.margin_bottom+self.rect.origin.y*/(row_rect.origin.y+row_rect.size.height> between_header_and_footer.location+between_header_and_footer.length) )
                {
                    if(j<row_data_count)
                    {
                        //把表格剩余部分补满
                        double height = between_header_and_footer.location+between_header_and_footer.length-(row_rect.origin.y);
                        if(height>0)
                        {
                            NSMutableDictionary * fixjson =[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:rowjson]];
                            fixjson[@"height"]=[NSNumber numberWithInt:height];
                            fixjson[@"expand"]=@"false";
                            PDFDrawable* fix_obj= [[GroupDrawable alloc] init:fixjson];
                            fix_obj.delegate = self.delegate;
                            [fix_obj Draw:context dataSource:nil ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
                        }

                        //越界，新起一页
                        if (self.delegate && [self.delegate respondsToSelector:@selector(outofPage:)]) {
                            [self.delegate outofPage:context];
                            dy=y;
                            if(header_repeat)
                            {
                                dy= [self DrawHeader:context dataSource:data ParentRect:p_rect startX:x startY:y flipHeight:flip_height range:between_header_and_footer dy:dy];
                                
                                //                            drawheader=true;
                            }
                            //  dx=0;
                        }
                    }
                    else
                    {
                        //把表格剩余部分补满
                        double height = between_header_and_footer.location+between_header_and_footer.length-(row_rect.origin.y);
                        if(height>0)
                        {
                            NSMutableDictionary * fixjson =[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:rowjson]];
                            fixjson[@"height"]=[NSNumber numberWithInt:height];
                            fixjson[@"expand"]=@"false";
                            PDFDrawable* fix_obj= [[GroupDrawable alloc] init:fixjson];
                            fix_obj.delegate = self.delegate;
                            [fix_obj Draw:context dataSource:nil ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
                        }

                        break;
                        //    goto finish_draw;
                    }
                    
                    
                }
            }
            else
            {
                if(j>row_data_count)
                    break;
            }

            
            
            [drawable_obj Draw:context dataSource:row_data ParentRect:(CGRect)pdfrect startX:0 startY:dy flipHeight:flip_height range:between_header_and_footer];
//            if([direction isEqualToString:@"H"])
//            {
//                dx+=row_rect.size.width;
//                if(dx+row_rect.size.width>parentrect.size.width)
                {
//                    dx=0;
                    dy+=row_rect.size.height;
                }
                
//            }
j++;
        }
        
    }
//finish_draw:
    [self DrawBound:context dataSource:data ParentRect:p_rect startX:x startY:y flipHeight:flip_height range:between_header_and_footer];
    return parentrect;
    //return CGPointMake(parentrect.origin.x+parentrect.size.width, parentrect.origin.y+parentrect.size.height);
    //    if (self.delegate && [self.delegate respondsToSelector:@selector(outofPage:)]) {
    //        [self.delegate outofPage:context];
    //    }
}
@end
