//
//  SimpleGride.m
//  Apex Mobile
//
//  Created by Ray on 14-3-4.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//
 
#import "SimpleGrid.h"
#import "Constant.h"


#define COLOR(R,G,B,A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]
@implementation SimpleGrid
@synthesize griddelegate;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // Initialization code
    }
    return self;
}
-(NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim
{
    NSScanner *theScanner = [NSScanner scannerWithString:html];
    NSString *text = nil;
    
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:
                [ NSString stringWithFormat:@"%@>", text]
                                               withString:@""];
    }
    
    return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;
}
-(void) initgrid :(PageData*) pageData
{
    for(UIView* v in self.subviews)
    {
        if(v.tag==200)// do not remove refresh control;
            continue;
        [v removeFromSuperview];
        
    }
    self.contentSize = CGSizeMake(0.0,0.0);
    self.hrefs = [[NSMutableDictionary alloc] init];
    self.pageData = pageData;
    self.hidden = TRUE;
    self.basetag = MAX_ROW*MAX_COLUMN;
    self.row_count  = [pageData get_count]+1;
    self.column_count = self.header_aname.count;
//    self.fullrowselect = true;
    
    self.top_line = 2;
    self.left_line =2;
    self.right_line =2;
    self.bottom_line=2;
    self.line = 1;
    
    int columns_width[MAX_COLUMN] ;
    for(int i=0;i<MAX_COLUMN;i++)
    {
        columns_width[i] = 10;
    }
    
    int row_offset = 20;
    
//    int padding_top = 2;
//    int padding_bottom = 2;
    int background_margin = 15;
    
 

    int padding_h = 10;
    int padding_v = 5;
//    int button_padding = 20;
    
    //        NSArray *columns_width = NsArray alloca(<#size_t#>)
    
//    UILabel * compute_item  = [UILabel alloc];
    
    
    
//     TouchLabel * compute_item  = [[TouchLabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0 )] ;
    UILabel * compute_item  = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0 )] ;
    
    NSMutableArray* values = [[NSMutableArray alloc] init];
    for(int i=0;i<self.column_count;i++)
    {
        
        [values addObject:self.header_aname[i]];
//        NSString* s=[self.header valueForKey:[self.header allKeys][i]];
//        [values  addObject:[self.header_aname[i]];
      //  [values setValue:[self.header valueForKey:[self.header allKeys][i]] forKey:nil];
        
    }

    for(int i=0;i<self.row_count-1;i++)
    {
        NSDictionary *objrecord = [pageData.records objectForKey:[NSString stringWithFormat:@"record%d",i]];
        
//        NSArray* keys= [objrecord allKeys];
        for(int j=0;j<self.column_count;j++)
        {
//            NSString* name =self.header_name[j];
            NSString* val = [objrecord valueForKey:self.header_name[j]];
            if([val isEqual:[NSNull null]])
                val=@"";
            if(val==nil)
                val=@"";
            if([val isEqualToString:@"null"])
                val=@"";
            NSString* text=[self flattenHTML:val trimWhiteSpace:true];
            [values addObject:text];
            if(! [text isEqualToString:val])
            {
                NSScanner *theScanner = [NSScanner scannerWithString:val];
                NSString *href = nil;
                

                    // find start of tag
                    [theScanner scanUpToString:@"https://" intoString:NULL] ;
                    // find end of tag
                    [theScanner scanUpToString:@"'" intoString:&href] ;
                [self.hrefs setObject:href forKey:text];
                
//                int i=0;
            }
            
        }
        
//        for(int j=0;j<keys.count;j++)
//        {
//            if([self.header valueForKey:keys[j]]!=nil)
//            {
//            }
//        }
    }
    
    
    
    
    
    for(int i=0;i<self.row_count;i++)
    {
    //    int column_offset = 0;
        for(int j=0;j<self.column_count;j++)
        {

//            int idx =i*self.column_count+j;
//            NSString* val=values[i*self.column_count+j];

            compute_item.text=  values[i*self.column_count+j];//[NSString stringWithFormat:@"item text %d",i*i+j*j];
            if(i==0)
                compute_item.textAlignment = NSTextAlignmentCenter;
            else
                compute_item.textAlignment = NSTextAlignmentLeft;
            
            
            
//              DebugLog(@"size: {x=%f , y=%f}",compute_item.frame.size.width,compute_item.frame.size.height);
            
            [compute_item sizeToFit];
            if(i==0&&j==0)
            {
                //row height only need compute once;
                row_offset = compute_item.frame.size.height+2*padding_v;
            }
            
//              DebugLog(@"size after fit: {x=%f , y=%f}",compute_item.frame.size.width,compute_item.frame.size.height);
            
            if(compute_item.frame.size.width+2*padding_h>columns_width[j])
                columns_width[j]=compute_item.frame.size.width+padding_h;
            
        }
    }
    int background_width = 0;
    for(int i=0;i<self.column_count;i++)
    {
        background_width+=columns_width[i];
        
    }
    background_width+=self.left_line;
    background_width+=self.right_line;
    background_width+=self.line*(self.column_count-1);

    
    long background_height= row_offset*self.row_count;
    background_height+=self.top_line;
    background_height+=self.bottom_line;
    background_height+=self.line*(self.row_count-1);
    
    UIView* backgroudView = [[UIView alloc] initWithFrame:CGRectMake(/*background_margin, background_margin,*/0,0, background_width, background_height )] ;
    backgroudView.backgroundColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];//[UIColor blueColor];
    backgroudView.alpha=1;
    
    int line_offset_row=0;
    for(int i=0;i<self.row_count;i++)
    {
        if(i==0)
            line_offset_row+=self.top_line;
        else
            line_offset_row+= self.line;

        int column_offset = 0;
        int line_offset_column=0;
        for(int j=0;j<self.column_count;j++)
        {
            
            if(j==0)
                line_offset_column+=self.left_line;
            else
                line_offset_column += self.line;
            
            
            TouchLabel * item  = [[TouchLabel alloc] initWithFrame:CGRectMake(column_offset+line_offset_column, row_offset*i+line_offset_row, columns_width[j], row_offset ) ] ;
            item.text=  values[i*self.column_count+j];//[NSString stringWithFormat:@"item text %d",i*i+j*j];
            if(i==0)
                compute_item.textAlignment = NSTextAlignmentCenter;
            else
                compute_item.textAlignment = NSTextAlignmentLeft;
            item.tag = self.basetag + MAX_ROW*i+j;
            
            if([self.hrefs valueForKey:item.text]!=nil)
                item.textColor =[UIColor blueColor];
            
            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LabelLong:)];
            longPress.minimumPressDuration = 0.8; //定义按的时间
            [item addGestureRecognizer:longPress];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(LabelTap:)];
//            tap.minimumPressDuration = 0.8; //定义按的时间
            [item addGestureRecognizer:tap];
            
            
            if(i>0)
            {
                if(i%2==1)
                    item.backgroundColor = [UIColor whiteColor];
                else
                    item.backgroundColor = COLOR(238,238,238,1.0);
            }
            else
                item.backgroundColor = [UIColor lightGrayColor];
            
            
            
//              DebugLog(@"size after fit: {x=%f , y=%f}",item.frame.size.width,item.frame.size.height);
            column_offset += columns_width[j];
            
            
            [backgroudView addSubview:item];
            

            
            
        }
    }
  
    CGSize contentSize;
    contentSize.height = self.superview.frame.size.height;//background_height+2*background_margin;
    contentSize.width = background_width+2*background_margin;
    self.contentSize = contentSize;
    
      DebugLog(@"background window : {x=%f , y=%f , width=%f , height=%f }",backgroudView.frame.origin.x,backgroudView.frame.origin.y ,backgroudView.frame.size.width,backgroudView.frame.size.height);
    [self addSubview:backgroudView];
    self.hidden = false;
    
}

#pragma mark - Label Gesture
- (void)drawSelect:(CGRect)rect
{
    
      DebugLog(@"drawSelect");
    CGContextRef context = UIGraphicsGetCurrentContext();
    //    CGRect rectt = CGRectMake(100 ,100, 100, 100);//坐标
    CGContextSetRGBFillColor(context, 0/ 255.0f, 0/ 255.0f, 0/ 255.0f,0.2);//颜色（RGB）,透明度
    CGContextFillRect(context, rect);
    // Drawing code
    
    //    CGContextRef context = UIGraphicsGetCurrentContext();
    //
    //    CGContextSetLineWidth(context, 2.0);
    //
    //    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor]);
    //
    //    CGContextMoveToPoint(context, rect.origin.x, rect.origin.y);
    //
    //    CGContextAddLineToPoint(context, rect.size.width, rect.size.height);
    //
    //    CGContextStrokePath(context);
    
}

-(void)LabelLong:(UILongPressGestureRecognizer*)gestureRecognizer{
    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
          DebugLog(@"长按事件");
        if(gestureRecognizer.view.tag - self.basetag < MAX_COLUMN) //header
            return;
//        CGRect rect;
//        if(self.fullrowselect)
//        {
//            
//            rect.origin.x= gestureRecognizer.view.superview.frame.origin.x+self.left_line;
//            rect.origin.y= gestureRecognizer.view.superview.frame.origin.y+self.left_line;
//        }
        //int idx = [t locationInView:self].y / d.cellHeight;
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.65];
        long row = (gestureRecognizer.view.tag-self.basetag) /100;
        if(self.fullrowselect)
        {
            
            for(int i=0;i<self.column_count;i++)
            {
                [self viewWithTag:(self.basetag+row*MAX_COLUMN+i)].alpha = 0.5;
            }
            for(int i=0;i<self.column_count;i++)
            {
                [self viewWithTag:(self.basetag+row*MAX_COLUMN+i)].alpha = 1.0;
            }
        }
        else
        {
            gestureRecognizer.view.alpha=0.5;
            gestureRecognizer.view.alpha=1;
        }
//		for(int i=0;i<[d.dataSource.titles count];i++){
//			UILabel *l = (UILabel*)[dataGridComponent viewWithTag:idx * d.cellHeight + i + 1000];
//			l.alpha = .5;
//		}
//		for(int i=0;i<[d.dataSource.titles count];i++){
//			UILabel *l = (UILabel*)[dataGridComponent viewWithTag:idx * d.cellHeight + i + 1000];
//			l.alpha = 1.0;
//		}
		[UIView commitAnimations];
        

        [griddelegate LongPress:gestureRecognizer.view _id:[self.pageData get_id:row-1]];//first row is header;
        

        
    }
}
-(void)LabelTap:(UILongPressGestureRecognizer*)gestureRecognizer {
    
       DebugLog(@"LabelTap tag = %ld",(long)gestureRecognizer.view.tag);
    if(gestureRecognizer.view.tag - self.basetag < MAX_COLUMN) //header
        return;
    TouchLabel* label = (TouchLabel*)gestureRecognizer.view;
    
    NSString * url =[self.hrefs valueForKey:label.text];
    if(url!=nil)
    {
        label.textColor = [UIColor purpleColor];
        [griddelegate Tap:label url:url];//first row is header;
    }

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
