//
//  BottomTableView.m
//  EugineAPISample
//
//  Created by aaab on 2023/02/03.
//

#import "BottomTableView.h"
#import "ComUtil.h"
#import "CustomTableViewCell.h"

@interface BottomTableView() < UITableViewDelegate , UITableViewDataSource , ICustomTableDelegate >
{
    UITableView *gridTableView;
    NSArray *arrayTableItems;
    NSMutableArray  *arrayWidth;
    NSMutableArray  *arrayTableTitle;
    NSArray  *arrayColumnKey;
    
    NSDictionary *dicTitleAttr;
    NSDictionary *dicCellAttr;
    
    id < IBottomTableDelegate > m_bottomDelegate;
}
@end

@implementation BottomTableView

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

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        CGFloat selfHeight = CGRectGetHeight(frame);
        CGFloat tableHeight = selfHeight * 0.6;
        
        UIView *tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(self.frame) - tableHeight)];
        [self addSubview:tapView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapGesture:)];
        [tapView addGestureRecognizer:tap];
        
        CGFloat yPos = selfHeight - tableHeight;
        gridTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, yPos, CGRectGetWidth(frame), tableHeight) style:UITableViewStylePlain];
        [gridTableView setBounces:NO];
        [gridTableView setDelegate:self];
        [gridTableView setDataSource:self];
        [gridTableView setRowHeight:35];
        [self addSubview:gridTableView];
        arrayWidth = [NSMutableArray array];
        
        [self setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.3]];
        
        NSParagraphStyle *style = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft lineSpacing:0];
        UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
        dicTitleAttr = [ComUtil makeFontAttrDictionary:font fontColor:[UIColor blackColor] underLine:NO letterSpace:0 paragraph:style];
        
        NSParagraphStyle *style2 = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft lineSpacing:0];
        UIFont *font2 = [UIFont fontWithName:@"HelveticaNeue-Light" size:16];
        dicCellAttr = [ComUtil makeFontAttrDictionary:font2 fontColor:[UIColor blackColor] underLine:NO letterSpace:0 paragraph:style2];
    }
    
    return self;
}

- (void)setBottomDelegate:(id <IBottomTableDelegate>)delegate
{
    m_bottomDelegate = delegate;
}

- (void)removeSuperView
{
    [UIView animateWithDuration:0.3 animations:^{
        [self->gridTableView setFrame:CGRectMake(0, CGRectGetHeight(self.frame), CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
        } completion:^(BOOL finished) {
            if (finished){
                [self removeFromSuperview];
            }
        }];

}

- (void)onTapGesture:(UITapGestureRecognizer*)gesture
{
    [self removeSuperView];
}

- (void)setTableViewItem:(NSArray*)array
{
    arrayTableItems = [NSMutableArray arrayWithArray:array];
    NSMutableArray *arrayMask = [NSMutableArray array];
    for (NSInteger i = 0 ; i < [array count]; i++) {
        NSDictionary *dicItem = array[i];
        
        if ( i == 0 ){
            arrayColumnKey = [dicItem.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
                return [obj1 compare:obj2];
            }];
            
            arrayWidth = [NSMutableArray array];
            for (NSInteger k = 0; k < [arrayColumnKey count]; k++) {
                [arrayWidth addObject:[NSNumber numberWithFloat:0.0f]];
            }
        }
        
        for ( NSInteger j = 0 ; j < [arrayColumnKey count] ; j++ ) {
            if ( i == 0 ){
                [arrayMask addObject:[NSNumber numberWithInteger:COLUMN_MASK_AUTO]];
            }
            
            NSNumber *numberWidth = arrayWidth[j];
            NSString *sKey = arrayColumnKey[j];
            NSString *sItem = dicItem[sKey];
            
            CGFloat width = [sKey sizeWithAttributes:dicTitleAttr].width + 40;
            if ([numberWidth floatValue] < width ){
                [arrayWidth replaceObjectAtIndex:j withObject:[NSNumber numberWithFloat:width]];
            }
            
            width = [sItem sizeWithAttributes:dicTitleAttr].width + 40;
            numberWidth = arrayWidth[j];
            if ([numberWidth floatValue] < width ){
                [arrayWidth replaceObjectAtIndex:j withObject:[NSNumber numberWithFloat:width]];
            }
        }
    }
    
    CustomTableViewCell *headerView = [[CustomTableViewCell alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), gridTableView.rowHeight * 1.5) reuseIdentifier:@"bottomtablecell"];
    [headerView setHeaderType:YES];
    [headerView setTitleAttr:dicTitleAttr];
    [headerView setBackgroundColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5]];
    [headerView setColumnWidth:arrayWidth title:arrayColumnKey mask:arrayMask];
    [gridTableView setTableHeaderView:headerView];
    [gridTableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (arrayTableItems == nil) return 0;
    
    return [arrayTableItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"bottomtablecell";
    UILabel *codelabel = nil;
    CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        [cell setDelegate:self];
        codelabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, CGRectGetWidth(cell.frame) - 40, CGRectGetHeight(cell.frame))];
        [codelabel setTag:1];
        [cell.contentView addSubview:codelabel];
        [cell setTitleAttr:dicCellAttr];
        [cell setBackgroundColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5]];
    }
    [cell setRowIndex:indexPath.row];
    NSDictionary *dic = [arrayTableItems objectAtIndex:indexPath.row];
    NSMutableArray *arrayCellItem = [NSMutableArray array];
    NSMutableArray *arrayMask = [NSMutableArray array];
    for (NSInteger i = 0 ; i < [arrayColumnKey count] ; i++){
        NSString *skey = arrayColumnKey[i];
        NSString *value = dic[skey];
        
        [arrayCellItem addObject:value];
        if ([skey rangeOfString:@"코드"].location != NSNotFound){
            [arrayMask addObject:[NSNumber numberWithInt:COLUMN_MASK_TEXT]];
        }else{
            [arrayMask addObject:[NSNumber numberWithInt:COLUMN_MASK_AUTO]];
        }
    }
    [cell setColumnWidth:arrayWidth title:arrayCellItem mask:arrayMask];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self selectItemIndex:indexPath.row];
}

- (void)didselectItem:(long)tag row:(NSInteger)rowIndex
{
    [self selectItemIndex:rowIndex];
}

- (void)selectItemIndex:(NSInteger)selectIndex
{
    NSDictionary *dicTable = arrayTableItems[selectIndex];
    
    if (m_bottomDelegate != nil){
        [m_bottomDelegate didSelectItem:dicTable object:self];
    }
    
    [self removeSuperView];
}

@end
