//
//  SearchFilterViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 14-7-25.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "SearchFilterViewController.h"
#import "FilterCellCadedate.h"
#import "FilterCellValue.h"
@interface SearchFilterViewController ()

@end

@implementation SearchFilterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCloseClick:)];
    self.navi_item.rightBarButtonItem = closeButton;
    // Do any additional setup after loading the view.
}
- (void)onCloseClick:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES
                             completion:^{
                                 
                                 
                             }];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)onSwitchTap:(UISwitch *)sender {
    
    //  UIView* sectionheader = sender.superview;
    int section = sender.superview.tag;
    if(section == 0 )
        return;
    for(int i=0;i<[[self.cadedate valueForKey:@"groups"]intValue];i++)
    {
        NSMutableDictionary* group_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"group_%d",i ]] mutableCopy];
        if(i==section-1)
        {
            if(sender.on)
            {
                [group_json setValue:@1 forKey:@"multi_select"];
                
                
            }
            else
            {
                [group_json setValue:@0 forKey:@"multi_select"];
                int count = [[group_json valueForKey:@"count"]intValue];
                for(int j=0;j<count;j++)
                {
                    NSMutableDictionary* item_json = [[group_json objectForKey:[NSString stringWithFormat:@"item_%d",j ]] mutableCopy];
                    [item_json setValue:@0 forKey:@"check"];
                    [group_json setObject:item_json forKey:[NSString stringWithFormat:@"item_%d",j ]];
                }
                
                
            }
            
        }
        else
        {
            [group_json setValue:@0 forKey:@"multi_select"];
            int count = [[group_json valueForKey:@"count"]intValue];
            for(int j=0;j<count;j++)
            {
                NSMutableDictionary* item_json = [[group_json objectForKey:[NSString stringWithFormat:@"item_%d",j ]] mutableCopy];
                [item_json setValue:@0 forKey:@"check"];
                [group_json setObject:item_json forKey:[NSString stringWithFormat:@"item_%d",j ]];
            }
        }
        
        [self.cadedate setObject:group_json forKey:[NSString stringWithFormat:@"group_%d",i]];
    }
    
    
    
    
    
    [self.tableView reloadData];
}
- (void)OnDone:(UIButton *)sender {
    
    int section = sender.superview.tag;
    NSDictionary* group_json = [self.cadedate objectForKey:[NSString stringWithFormat:@"group_%d",section-1 ]];
 //   int multi_select = [[group_json valueForKey:@"multi_select"] intValue];


    
    
    NSMutableDictionary * value_json = self.value;
    if(value_json==nil)
        value_json=[[NSMutableDictionary alloc] init];
    int groups = [[value_json valueForKey:@"groups"] intValue];
    [value_json setValue:@(groups+1) forKey:@"groups"];
    
    NSMutableDictionary * value_group_json = [[NSMutableDictionary alloc] init];
    
    int count = [[group_json valueForKey:@"count"]intValue];
    int check_count=0;
    NSString * title = [[group_json valueForKey:@"title"] stringByAppendingString:@":"] ;
    for(int i=0;i<count;i++)
    {
            NSDictionary* item_json = [group_json objectForKey:[NSString stringWithFormat:@"item_%d",i]] ;
    
        int check = [[item_json valueForKey:@"check"] intValue];
        if(check==0)
            continue;
        check_count++;

    title = [title stringByAppendingString:[item_json valueForKey:@"title"]];
        title = [title stringByAppendingString:@","];
    
    
    

    [value_group_json setValue:[item_json valueForKey:@"val"] forKey:[NSString stringWithFormat:@"val_%d",check_count]];
    
    }
    if(check_count<1)
        return;
    NSString* key = [group_json valueForKey:@"key"];
    if(title.length>=1)
        title=[title substringToIndex:title.length-1];
    [value_group_json setValue:title forKey:@"title"];
    [value_group_json setValue:@(check_count) forKey:@"count" ];
    [value_group_json setValue:key forKey:@"key" ];
    [value_json setObject:value_group_json forKey:[NSString stringWithFormat:@"group_%d",groups]];
    self.value = value_json;
    
//    NSError *error = nil;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value_json
//                                                       options:NSJSONWritingPrettyPrinted
//                                                         error:&error];
//    
//    
//    //     NSData * d = [NSData alloc] initwithd
//    NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSLog(result);
    [self closewindow];
}

- (IBAction)OnDeleteValue:(UIButton *)sender {
    int groups = [[self.value valueForKey:@"groups"]intValue];
    if(groups==1)
    {
        self.value = nil;
        [self closewindow];
    }
    else
    {
        
        FilterCellValue *cell  = (FilterCellValue *) sender.superview.superview.superview;
        //      NSIndexPath*  indexPath = [self.tableView indexPathForCell:cell];
        
        NSMutableDictionary * value_json=[[NSMutableDictionary alloc] init];
        int count = 0;
        for(int i=0;i<groups;i++)
        {
            NSDictionary* group_json = [self.value objectForKey:[NSString stringWithFormat:@"group_%d",i]];
            NSString* title = [group_json valueForKey:@"title"];
            if(![title isEqualToString:cell.labelTitle.text])
            {
                [value_json setObject:group_json forKey:[NSString stringWithFormat:@"group_%d",count]];
                count++;
                
                
            }
            
        }
        [value_json setValue:@(count) forKey:@"groups"];
        self.value = value_json;
        [self closewindow];
        
    }
    
    
}

#pragma mark - Table view data source

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)];
    
    //    myView.backgroundColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 22)];
    //  titleLabel.textColor=[UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    
    if(section==0)
        titleLabel.text= @"in use filters";
    else
    {
        NSDictionary* group_json =[self.cadedate objectForKey:[NSString stringWithFormat:@"group_%ld",(long)section-1]];
        titleLabel.text= [group_json valueForKey:@"title"];
        int multi_select = [[group_json valueForKey:@"multi_select"] intValue];
        
        UILabel *switch_Label = [[UILabel alloc] initWithFrame:CGRectMake(tableView.bounds.size.width-51-10-110, 0, 110, 22)];
        //  titleLabel.textColor=[UIColor whiteColor];
        switch_Label.backgroundColor = [UIColor clearColor];
        switch_Label.text=@"Multi Select";
        //      switch_Label.text
        
        
        
        UISwitch* btn_switch = [[UISwitch alloc] initWithFrame:CGRectMake(tableView.bounds.size.width-51-10, 0, 51, 31)];
        myView.tag = section;
        [btn_switch addTarget:self action:@selector(onSwitchTap:) forControlEvents:UIControlEventValueChanged];
        
        
        if(multi_select==1)
        {
            btn_switch.on=true;
            // CGRect rt = btn_switch.frame;
            btn_switch.frame=CGRectOffset(btn_switch.frame, -160, 0);
            switch_Label.frame=CGRectOffset(switch_Label.frame, -160, 0);
            
            UIButton* btn_done = [UIButton buttonWithType:UIButtonTypeSystem];
            btn_done.frame =CGRectMake(tableView.bounds.size.width-50-10, 0, 50, 30);
            // btn_done.titleLabel.text = @"Done";
            [btn_done setTitle:@"Done" forState:UIControlStateNormal];
            //      btn_done.buttonType = UIButtonTypeSystem;
            //  btn_done.backgroundColor =[UIColor redColor];
            
            [btn_done addTarget:self action:@selector(OnDone:) forControlEvents:UIControlEventTouchUpInside];
            [myView addSubview:btn_done];
        }
        [myView addSubview:switch_Label];
        [myView addSubview:btn_switch];
    }
    [titleLabel sizeToFit];
    //    if(section==0)
    //       titleLabel.text=NSLocalizedString(@"multi select", nil);
    //    else
    //        titleLabel.text=NSLocalizedString(@"hide_items", nil);
    //    [titleLabel sizeToFit];
    [myView addSubview:titleLabel];
    //
    return myView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.cadedate valueForKey:@"groups"] intValue]+1;
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    if(section==0)
//        return @"in use filters";
//    else
//    {
//        NSDictionary* group_json =[self.cadedate objectForKey:[NSString stringWithFormat:@"group_%d",section-1]];
//        return [group_json valueForKey:@"title"];
//    }
//}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section==0 && self.value==nil)
        return 0;
    return 44;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
//{
//    return 88;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0)
        if(self.value==nil)
            return 0;
        else
            return [[self.value valueForKey:@"groups"] intValue];
        else
        {
            NSDictionary* group_json =[self.cadedate objectForKey:[NSString stringWithFormat:@"group_%d",section-1]];
            return [[group_json valueForKey:@"count"] intValue];
        }
    
    
    
    
    
}
-(void) closewindow
{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(SearchFilterReturn:)]) {
        [self.delegate SearchFilterReturn:self.value];
    }
    
    
    [self dismissViewControllerAnimated:YES
                             completion:^{
                                 
                                 
                             }];}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section==0)
    {
        NSString* CellIdentifier = @"FilterCellValue";
        
        FilterCellValue * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        NSDictionary* group_json = [self.value objectForKey:[NSString stringWithFormat:@"group_%ld",(long)indexPath.row ]];
        cell.labelTitle.text=[group_json valueForKey:@"title"];
        //lacell.textLabel.text =[group_json valueForKey:@"title"];
        return cell;
    }
    else
    {
        NSString* CellIdentifier = @"FilterCellCadedate";
        
        FilterCellCadedate * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        NSDictionary* group_json = [self.cadedate objectForKey:[NSString stringWithFormat:@"group_%d",indexPath.section-1 ]];
        NSDictionary* item_json = [group_json objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row ]];
        NSString* title = [item_json valueForKey:@"title"];
        
        cell.textLabel.text = title;
        
        
        int check = [[item_json valueForKey:@"check" ] intValue];
        if(check==1)
            cell.img_checkmark.hidden=false;
        else
            cell.img_checkmark.hidden=true;

        
        return cell;
        
    }
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = (UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];

    cell.selected = false;
    
    
    
    if(indexPath.section==0)
        return;
    else
    {
        
        NSMutableDictionary* group_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"group_%d",indexPath.section-1 ]] mutableCopy];
        int multi_select = [[group_json valueForKey:@"multi_select"] intValue];
        NSMutableDictionary* item_json = [[group_json objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row ]] mutableCopy];
        if(multi_select==1)
        {
            int check = [[item_json valueForKey:@"check" ] intValue];
            if(check==1)
            {
                cell.accessoryType = UITableViewCellAccessoryNone;
                [item_json setValue:@0 forKey:@"check"];
                
            }
            else
            {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                [item_json setValue:@1 forKey:@"check"];
            }
            [group_json setObject:item_json forKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row ]];
            [self.cadedate setObject:group_json forKey:[NSString stringWithFormat:@"group_%ld",(long)indexPath.section-1 ]];
            [self.tableView reloadData];
        }
        else
        {
            NSMutableDictionary * value_json = self.value;
            if(value_json==nil)
                value_json=[[NSMutableDictionary alloc] init];
            int groups = [[value_json valueForKey:@"groups"] intValue];
            [value_json setValue:@(groups+1) forKey:@"groups"];
            
            
            
            NSMutableDictionary * value_group_json = [[NSMutableDictionary alloc] init];
            //      NSString* ttt =[group_json valueForKey:@"title"];
            NSString * title = [[[group_json valueForKey:@"title"] stringByAppendingString:@":"] stringByAppendingString:[item_json valueForKey:@"title"]];
            
            NSString* key = [group_json valueForKey:@"key"];
            
            [value_group_json setValue:title forKey:@"title"];
            [value_group_json setValue:@1 forKey:@"count" ];
            [value_group_json setValue:key forKey:@"key" ];
            [value_group_json setValue:[item_json valueForKey:@"val"] forKey:@"val_0"];
            [value_json setObject:value_group_json forKey:[NSString stringWithFormat:@"group_%d",groups]];
            
            self.value = value_json;
            
            NSError *error = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value_json
                                                               options:NSJSONWritingPrettyPrinted
                                                                 error:&error];
            
            
            //     NSData * d = [NSData alloc] initwithd
            NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(result);
            [self closewindow];
            
            
            
        }
        
        
    }
 
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
