
//The MIT License (MIT)
//
//Copyright (c) 2013 Rafał Augustyniak
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#import "RAViewController.h"
#import "RATreeView.h"
//#import "RADataObject.h"
#import "AppDelegate.h"
#import "MainViewController.h"
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


@interface RAViewController () <RATreeViewDelegate, RATreeViewDataSource,UIGestureRecognizerDelegate>

//@property (strong, nonatomic) NSArray *data;
@property (strong,nonatomic)NSDictionary* categoryMenu;
@property (strong, nonatomic) id expanded;
@property (weak, nonatomic) RATreeView *treeView;


@end

@implementation RAViewController




-(void) reload_container_getdata:(bool) update_data
{
    
    [super reload_container_getdata:update_data];
//    if(update_data)
//        [self reload_data];
//    else
//    {
//        [self.itemListTable reloadData];
//        [self refresh_total];
//    }
    
    if(update_data==false)
        return;
        UIApplication * app = [UIApplication sharedApplication];
    
      AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        NSDictionary* category=[iSalesNetwork request_Cagegory];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if([[category valueForKey:@"result"] intValue]==2)
            {
                appDelegate.categoryMenu = category;
                [self SetMenu:appDelegate.categoryMenu ];
            }
            else
                if([[category valueForKey:@"result"] intValue]==RESULT_NET_ERROR)
                {
                    [self SetMenu:nil ];
                }
                else
                {
                    [RAUtils message_alert:[category valueForKey:@"err_msg"]  title:@"Load Category Menu" controller:self] ;
                }
            
            
            
        });
    });
    
    
    
}


-(void) SetMenu:(NSDictionary*) menu
{
    if(menu==nil)
    {
        self.label_net_err.hidden=false;
        self.treeView.hidden = true;
        
    }
    else
    {
        self.label_net_err.hidden=true;
        self.treeView.hidden = false;
    }
    self.categoryMenu = menu;
    [self.treeView reloadData];
}
- (IBAction)CloseClick:(id)sender {
    
    [self dismissViewControllerAnimated:true completion:nil];
    

}
- (void)viewDidLoad
{
  [super viewDidLoad];
    
    if(self.categoryMenu==nil)
    self.refresh_type = REFRESH_DATA;
    else
    self.refresh_type = REFRESH_VIEW;
    
    self.label_net_err.layer.borderColor = [UIColor darkGrayColor].CGColor;
    self.label_net_err.layer.borderWidth = 2.0;
    self.label_net_err.layer.cornerRadius=15;
    self.label_net_err.layer.masksToBounds=true;
    
    
    
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refresh_btn_click:)];
    //            tap.minimumPressDuration = 0.8; //定义按的时间
    [self.label_net_err addGestureRecognizer:tap];
    
    
    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector( CloseClick:)];
    
    self.navigationItem.rightBarButtonItem = closeButton;

//    CGRect frame = self.view.frame;
//    frame.origin.y = 200;//self.headerview.frame.size.height;
//    frame.size.height = frame.size.height - self.headerview.frame.size.height;
    

    
  
  RATreeView *treeView = [[RATreeView alloc] initWithFrame:self.treeContainer.frame];
  
  treeView.delegate = self;
  treeView.dataSource = self;
  treeView.separatorStyle = RATreeViewCellSeparatorStyleSingleLine;
  
  [treeView reloadData];
//  [treeView expandRowForItem:phone withRowAnimation:RATreeViewRowAnimationLeft]; //expands Row
  [treeView setBackgroundColor: [UIColor whiteColor]];
  
  self.treeView = treeView;
  [self.treeContainer addSubview:treeView];
    
    
    
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handletapPressGesture:)];
//    AppDelegate *app = [[UIApplication sharedApplication] delegate];
//    [app.window addGestureRecognizer:tapGesture];
//    tapGesture.delegate = self;
//    self.tapGesture = tapGesture;
    
}
//-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
//{
//    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
//        //做自己想做的事
//        return NO;
//    }
//    DebugLog(NSStringFromClass([touch.view class]));
//    return YES;
//}
//
//-(void)handletapPressGesture:(UITapGestureRecognizer*)sender{
//    CGPoint point = [sender locationInView:self.view];
//    if (point.x<self.view.frame.origin.x || point.x >self.view.frame.origin.x+self.view.frame.size.width||point.y<self.view.frame.origin.y||point.y>self.view.frame.origin.y+self.view.frame.size.height) {
//        [self dismissViewControllerAnimated:YES
//                                 completion:^{
//                                     //一定要移除手势 否则下次 没有子视图的时候 点击 会崩溃拉
//                                     AppDelegate *app = [[UIApplication sharedApplication] delegate];
//                                     [app.window removeGestureRecognizer:sender];
//                                 }];
//    }
//    
//}
- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  
//  if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
//    CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
//    float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;
//    self.treeView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
//    self.treeView.contentOffset = CGPointMake(0.0, -heightPadding);
//  }
  
  self.treeView.frame = self.treeContainer.bounds;
}

#pragma mark TreeView Delegate methods
- (CGFloat)treeView:(RATreeView *)treeView heightForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
  return 47;
}

- (NSInteger)treeView:(RATreeView *)treeView indentationLevelForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
  return 3 * treeNodeInfo.treeDepthLevel;
}

- (BOOL)treeView:(RATreeView *)treeView shouldExpandItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
  return YES;
}

- (BOOL)treeView:(RATreeView *)treeView shouldItemBeExpandedAfterDataReload:(id)item treeDepthLevel:(NSInteger)treeDepthLevel
{
  if ([item isEqual:self.expanded]) {
    return YES;
  }
  
  return NO;
}
- (void)treeView:(RATreeView *)treeView didSelectRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    
    NSDictionary *data = item;
    int count = [[data valueForKey:@"count"] intValue];
    if(count==0)
    {
        NSString* category = [data valueForKey:@"id"];
        
            if (self.CateMenu_delegate && [self.CateMenu_delegate respondsToSelector:@selector(SelectCategory:)]) {
            [self.CateMenu_delegate SelectCategory:category];
        }
       /* MainViewController* pvc = (MainViewController*)self.rootViewController;
        [pvc switchToCagegory:category];*/
        [self dismissViewControllerAnimated:YES
                                 completion:^{
                                     //一定要移除手势 否则下次 没有子视图的时候 点击 会崩溃拉
//                                     AppDelegate *app = [[UIApplication sharedApplication] delegate];
//                                     [app.window removeGestureRecognizer:self.tapGesture];
                                 }];
    }
    
//    if (item == nil) {
//        NSDictionary * ret =[self.categoryMenu objectForKey:[NSString stringWithFormat:@"category_%d",index] ];
//      
//    }
//    else
//        data=[data objectForKey:[NSString stringWithFormat:@"category_%d",index]];
    DebugLog(@"menu select %@",data);
}

- (void)treeView:(RATreeView *)treeView willDisplayCell:(UITableViewCell *)cell forItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
  if (treeNodeInfo.treeDepthLevel == 0) {
    cell.backgroundColor = [UIColor whiteColor];
  } else if (treeNodeInfo.treeDepthLevel == 1) {
    cell.backgroundColor = UIColorFromRGB(0xD1EEFC);
  } else if (treeNodeInfo.treeDepthLevel == 2) {
    cell.backgroundColor = UIColorFromRGB(0xE0F8D8);
  }
}

#pragma mark TreeView Data Source

- (UITableViewCell *)treeView:(RATreeView *)treeView cellForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
 // NSInteger numberOfChildren = [treeNodeInfo.children count];
  
  UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
//    if(numberOfChildren>0)
//  cell.detailTextLabel.text = [NSString stringWithFormat:@"Number of children %@", [@(numberOfChildren) stringValue]];
  cell.textLabel.text = [((NSDictionary *)item) valueForKey:@"title"];
  cell.selectionStyle = UITableViewCellSelectionStyleNone;
  
  if (treeNodeInfo.treeDepthLevel == 0) {
    cell.detailTextLabel.textColor = [UIColor blackColor];
  }
  
  return cell;
}

- (NSInteger)treeView:(RATreeView *)treeView numberOfChildrenOfItem:(id)item
{
  if (item == nil) {
      return [[self.categoryMenu valueForKey:@"count" ] intValue];
 //   return [self.data count];
  }
  
    NSDictionary* data = item;
    return [[data valueForKey:@"count"] intValue];
//  RADataObject *data = item;
//  return [data.children count];
}

- (id)treeView:(RATreeView *)treeView child:(NSInteger)index ofItem:(id)item
{
  NSDictionary *data = item;
    
  if (item == nil) {
      NSDictionary * ret =[self.categoryMenu objectForKey:[NSString stringWithFormat:@"category_%ld",(long)index] ];
     return  ret;
  }
  
  return[data objectForKey:[NSString stringWithFormat:@"category_%ld",(long)index]];
    /*
     
     RADataObject *data = item;
     if (item == nil) {
     return [self.data objectAtIndex:index];
     }
     
     return [data.children objectAtIndex:index];
     */
}

@end
