//
//  NIDropDown.m
//  NIDropDown
//
//  Created by Bijesh N on 12/28/12.
//  Copyright (c) 2012 Nitor Infotech. All rights reserved.
//

#import "NIDropDown.h"
#import "QuartzCore/QuartzCore.h"
#import "iSalesDB.h"

@interface NIDropDown ()
@property(nonatomic, strong) UITableView *table;
@property(nonatomic, strong) UIButton *btnSender;
//@property(nonatomic, retain) NSArray *list;
//@property(nonatomic, retain) NSArray *imageList;
@end

@implementation NIDropDown
@synthesize table;
@synthesize btnSender;
//@synthesize list;
//@synthesize imageList;
@synthesize delegate;
@synthesize animationDirection;
//
//- (id)showDropDown:(UIButton *)b:(CGFloat *)height:(NSArray *)arr:(NSArray *)imgArr:(NSString *)direction {
//    btnSender = b;
//    animationDirection = direction;
//    self.table = (UITableView *)[super init];
//    if (self) {
//        // Initialization code
//        CGRect btn = b.frame;
//        self.list = [NSArray arrayWithArray:arr];
//        self.imageList = [NSArray arrayWithArray:imgArr];
//        if ([direction isEqualToString:@"up"]) {
//            self.frame = CGRectMake(btn.origin.x, btn.origin.y, btn.size.width, 0);
//            self.layer.shadowOffset = CGSizeMake(-5, -5);
//        }else if ([direction isEqualToString:@"down"]) {
//            self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, 0);
//            self.layer.shadowOffset = CGSizeMake(-5, 5);
//        }
//        
//        self.layer.masksToBounds = NO;
//        self.layer.cornerRadius = 8;
//        self.layer.shadowRadius = 5;
//        self.layer.shadowOpacity = 0.5;
//        
//        table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, btn.size.width, 0)];
//        table.delegate = self;
//        table.dataSource = self;
//        table.layer.cornerRadius = 5;
//        table.backgroundColor = [UIColor colorWithRed:0.239 green:0.239 blue:0.239 alpha:1];
//        table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//        table.separatorColor = [UIColor grayColor];
//        
//        [UIView beginAnimations:nil context:nil];
//        [UIView setAnimationDuration:0.5];
//        if ([direction isEqualToString:@"up"]) {
//            self.frame = CGRectMake(btn.origin.x, btn.origin.y-*height, btn.size.width, *height);
//        } else if([direction isEqualToString:@"down"]) {
//            self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, *height);
//        }
//        table.frame = CGRectMake(0, 0, btn.size.width, *height);
//        [UIView commitAnimations];
//        [b.superview addSubview:self];
//        [self addSubview:table];
//    }
//    return self;
//}
- (id)showDropDown:(UIView*)container based:(UIButton *)b height:(CGFloat )height data:(NSDictionary *)json direction:(NSString *)direction current_sel:(long) current_sel {
    self.current_sel = current_sel;
    btnSender = b;
    animationDirection = direction;
    self.table = (UITableView *)[super init];
    if (self) {
        // Initialization code
        CGRect btn = b.frame;
//        self.list = [NSArray arrayWithArray:arr];
//        self.imageList = [NSArray arrayWithArray:imgArr];
        self.selector = json;
        if ([direction isEqualToString:@"up"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y, btn.size.width, 0);
            self.layer.shadowOffset = CGSizeMake(-5, -5);
        }else if ([direction isEqualToString:@"down"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, 0);
            self.layer.shadowOffset = CGSizeMake(-5, 5);
        }
        
        self.layer.masksToBounds = NO;
       // self.layer.cornerRadius = 8;
        self.layer.shadowRadius = 5;
        self.layer.shadowOpacity = 0.5;
        
        table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, btn.size.width, 0)];
        table.delegate = self;
        table.dataSource = self;
       // table.layer.cornerRadius = 5;
        table.backgroundColor = [UIColor colorWithRed:0.239 green:0.239 blue:0.239 alpha:1];
        table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        if ([table respondsToSelector:@selector(setSeparatorInset:)]) {
            [table setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([table respondsToSelector:@selector(setLayoutMargins:)]) {
            [table setLayoutMargins:UIEdgeInsetsZero];
        }
        table.separatorColor = [UIColor grayColor];
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        if ([direction isEqualToString:@"up"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y-height, btn.size.width, height);
        } else if([direction isEqualToString:@"down"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, height);
        }
        table.frame = CGRectMake(0, 0, btn.size.width, height);
        [UIView commitAnimations];
        self.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        [container addSubview:self];
        [self addSubview:table];
        
    }
    return self;
}
-(void)hideDropDown:(UIButton *)b {
    CGRect btn = b.frame;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    if ([animationDirection isEqualToString:@"up"]) {
        self.frame = CGRectMake(btn.origin.x, btn.origin.y, btn.size.width, 0);
    }else if ([animationDirection isEqualToString:@"down"]) {
        self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, 0);
    }
    table.frame = CGRectMake(0, 0, btn.size.width, 0);
    [UIView commitAnimations];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return      [[self.selector valueForKey:@"count"] intValue];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* selectorname = [self.selector valueForKey:@"name"] ;
    static NSString *CellIdentifier = @"Cell";
  //      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textAlignment = NSTextAlignmentLeft;
    }
//    NSString *CellIdentifier = @"SelectorCell";

    
    if(self.current_sel==indexPath.row)
    {
        cell.contentView.layer.borderColor = [UIColor orangeColor].CGColor;
        cell.contentView.layer.borderWidth = 1.0;
        cell.contentView.layer.cornerRadius=5;
        cell.contentView.layer.masksToBounds=true;
    }
    else
    {
        cell.contentView.layer.borderWidth = 0.0;
    }
    
    NSDictionary* item = [self.selector objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
    
    cell.imageView.image=[UIImage imageNamed:@"loading_s"];
    cell.textLabel.text=[NSString stringWithFormat:@"%@: %@",selectorname,[item valueForKey:@"title"]];
    NSString* img_url = [item valueForKey:@"pic_url"];
    NSString* file_name=[img_url lastPathComponent];
    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
    if(img_data!=nil)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage * img =[UIImage imageWithData:img_data];
            cell.imageView.image=img;
        });
    }
    else
    {
        NSData*  downloadimg_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:img_url]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            if(downloadimg_data!=nil)
            {
                
                [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                
                UIImage * img =[UIImage imageWithData:downloadimg_data];
                cell.imageView.image=img;
            }
            else
                cell.imageView.image=[UIImage imageNamed:@"notfound_s"];
            
        });
    }
    //        cell.selector_valLabel.text =[[section_json objectForKey:@"selector"] valueForKey:@"name"];
    
    
  //  cell.textLabel.textColor = [UIColor whiteColor];
    
    UIView * v = [[UIView alloc] init];
    v.backgroundColor = [UIColor grayColor];
    cell.selectedBackgroundView = v;
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self hideDropDown:btnSender];
    
    if(self.selectChanged)
    {
        self.selectChanged(indexPath.row);
    }
    
//    UITableViewCell *c = [tableView cellForRowAtIndexPath:indexPath];
//    [btnSender setTitle:c.textLabel.text forState:UIControlStateNormal];
//    
//    for (UIView *subview in btnSender.subviews) {
//        if ([subview isKindOfClass:[UIImageView class]]) {
//            [subview removeFromSuperview];
//        }
//    }
//    imgView.image = c.imageView.image;
//    imgView = [[UIImageView alloc] initWithImage:c.imageView.image];
//    imgView.frame = CGRectMake(5, 5, 25, 25);
//    [btnSender addSubview:imgView];
//    [self myDelegate];
}

- (void) myDelegate {
    [self.delegate niDropDownDelegateMethod:self];
}

-(void)dealloc {
//    [super dealloc];
//    [table release];
//    [self release];
}

@end
