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

#import "CustomTableViewCell.h"
#import "ComUtil.h"
#import "CondItemInfo.h"
#import "CondSearchInfo.h"
#import "Util.h"



@interface CustomTableViewCell() < UIScrollViewDelegate >
{
    NSDictionary *dicTitleAttr;
    UIScrollView *cellScrollView;
    NSInteger nRowIndex;
    id <ICustomTableDelegate> m_tableDelegate;
    NSString    *sNotiName;
    CGPoint     scrolllPoint;
    
    BOOL        isHeaderType;
}

@end

@implementation CustomTableViewCell

- (void)setRowIndex:(NSInteger)index
{
    nRowIndex = index;
}

- (void)setDelegate:(id <ICustomTableDelegate>)delegate
{
    m_tableDelegate = delegate;
}

- (void)setHeaderType:(BOOL)type
{
    isHeaderType = type;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiTableViewCellScroll:) name:NotiTableViewCellScroll object:nil];
    }
    return self;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self){
        sNotiName = [NSString stringWithFormat:@"%@%@" , reuseIdentifier , NotiTableViewCellScroll];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiTableViewCellScroll:) name:sNotiName object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:sNotiName object:nil];
}

- (void)notiTableViewCellScroll:(NSNotification*)noti
{
    if ([noti object] == cellScrollView) return;
    NSDictionary *dicUseInfo = [noti userInfo];
    CGPoint point = CGPointFromString(dicUseInfo[@"scrollpos"]);
    scrolllPoint = point;
    [ComUtil setString:NSStringFromCGPoint(scrolllPoint) key:sNotiName];
    [cellScrollView setContentOffset:point];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSDictionary *dic =[NSDictionary dictionaryWithObject:NSStringFromCGPoint(scrollView.contentOffset) forKey:@"scrollpos"];
    [[NSNotificationCenter defaultCenter] postNotificationName:sNotiName object:cellScrollView userInfo:dic];
}

- (void)setTitleAttr:(NSDictionary*)dicAttr
{
    dicTitleAttr = dicAttr;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    if (cellScrollView != nil){
        [cellScrollView setFrame:self.bounds];
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)singleTap:(UITapGestureRecognizer *)gesture {
    @try {
        if (m_tableDelegate != nil)
        {
            [m_tableDelegate didselectItem:self.tag row:nRowIndex];
        }
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
}

- (void)setColumnWidth:(NSArray*)width
{
    CGFloat totalWidth = 0.0f;
    for (NSNumber *subNum in width) {
        totalWidth += [subNum floatValue];
    }
    
    if ( totalWidth > CGRectGetWidth(self.frame)){
        cellScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        [cellScrollView setBounces:NO];
        [cellScrollView setDelegate:self];
        [cellScrollView setShowsHorizontalScrollIndicator:NO];
        [cellScrollView setContentSize:CGSizeMake(totalWidth, 0)];
        [self.contentView addSubview:cellScrollView];
        
        UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        singleTapGestureRecognizer.numberOfTapsRequired = 1;
        singleTapGestureRecognizer.enabled = YES;
        singleTapGestureRecognizer.cancelsTouchesInView = NO;
        [cellScrollView addGestureRecognizer:singleTapGestureRecognizer];
    }
    
    CGFloat xPos = 0;
    for (NSInteger i = 0; i < [width count]; i++) {
        NSNumber *numberWidth = width[i];
        UILabel *labelColumn = [[UILabel alloc] initWithFrame:CGRectMake(xPos, 0, [numberWidth floatValue], CGRectGetHeight(self.frame))];
        [labelColumn setTextAlignment:NSTextAlignmentLeft];
        [labelColumn setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
        [labelColumn setTag:i + 100];
        if ( cellScrollView == nil){
            [self.contentView addSubview:labelColumn];
        }else{
            [cellScrollView addSubview:labelColumn];
        }
        xPos += [numberWidth floatValue];
    }
    
    NSString *sString = [ComUtil getString:sNotiName basic:NSStringFromCGPoint(CGPointZero)];
    CGPoint point = CGPointFromString(sString);
    if ( !CGPointEqualToPoint(point, CGPointZero))
        [cellScrollView setContentOffset:CGPointFromString(sString)];
}

- (void)setColumnTitle:(NSArray*)title
{
    for (NSInteger i = 0; i < [title count]; i++) {
        UILabel *labelColumn = nil;
        if ( cellScrollView == nil){
            labelColumn = [self.contentView viewWithTag:i+100];
        }else{
            labelColumn = [cellScrollView viewWithTag:i+100];
        }
        if (title != nil){
            NSString *sTitle = title[i];
            NSAttributedString *sAttrString = [[NSAttributedString alloc] initWithString:sTitle attributes:dicTitleAttr];
            [labelColumn setAttributedText:sAttrString];
        }
    }
    NSString *sString = [ComUtil getString:sNotiName basic:NSStringFromCGPoint(CGPointZero)];
    CGPoint point = CGPointFromString(sString);
    if ( !CGPointEqualToPoint(point, CGPointZero))
        [cellScrollView setContentOffset:CGPointFromString(sString)];
}

- (void)setColumnWidth:(NSArray*)width title:(NSArray*)title mask:(NSArray*)masks
{
    CGFloat totalWidth = 0.0f;
    for (NSNumber *subNum in width) {
        totalWidth += [subNum floatValue];
    }
    
    if ( totalWidth > CGRectGetWidth(self.frame)){
        cellScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        [cellScrollView setBounces:NO];
        [cellScrollView setDelegate:self];
        [cellScrollView setShowsHorizontalScrollIndicator:NO];
        [cellScrollView setContentSize:CGSizeMake(totalWidth, 0)];
        [self.contentView addSubview:cellScrollView];
        
        UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        singleTapGestureRecognizer.numberOfTapsRequired = 1;
        singleTapGestureRecognizer.enabled = YES;
        singleTapGestureRecognizer.cancelsTouchesInView = NO;
        [cellScrollView addGestureRecognizer:singleTapGestureRecognizer];
    }
    
    CGFloat xPos = 0;
    for (NSInteger i = 0; i < [width count]; i++) {
        NSNumber *numberWidth = width[i];
        UILabel *labelColumn = [[UILabel alloc] initWithFrame:CGRectMake(xPos, 0, [numberWidth floatValue], CGRectGetHeight(self.frame))];
        [labelColumn setLineBreakMode:NSLineBreakByCharWrapping];
        [labelColumn setTextAlignment:NSTextAlignmentLeft];
        [labelColumn setFont:[Util fontType:LIGHT size:13]];
        [labelColumn setTag:i + 100];
        if ( cellScrollView == nil){
            [self.contentView addSubview:labelColumn];
        }else{
            [cellScrollView addSubview:labelColumn];
        }
        COLUMN_MASK mask = COLUMN_MASK_AUTO;
        if (masks != nil )
            mask = [masks[i] integerValue];
        if (title != nil){
            NSString *sTitle = title[i];
            if ( !isHeaderType ){
                if (mask == COLUMN_MASK_AUTO){
                    if ([Util isNumber:sTitle]){
                        NSParagraphStyle *style = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentRight lineSpacing:0];
                        [dicTitleAttr setValue:style forKey:NSParagraphStyleAttributeName];
                        [labelColumn setTextAlignment:NSTextAlignmentRight];
                        sTitle = [Util getCurrencyFromString:sTitle formatter:nil];
                        sTitle = [sTitle stringByAppendingString:@" "];
                    }else{
                        NSParagraphStyle *style = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentLeft lineSpacing:0];
                        [dicTitleAttr setValue:style forKey:NSParagraphStyleAttributeName];
                        [labelColumn setTextAlignment:NSTextAlignmentRight];
                        sTitle = [@" " stringByAppendingString:sTitle];
                    }
                }else if (mask == COLUMN_MASK_TEXT){
                    NSParagraphStyle *style = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentLeft lineSpacing:0];
                    [dicTitleAttr setValue:style forKey:NSParagraphStyleAttributeName];
                    [labelColumn setTextAlignment:NSTextAlignmentRight];
                    sTitle = [@" " stringByAppendingString:sTitle];
                }else if (mask == COLUMN_MASK_NUM){
                    NSParagraphStyle *style = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentRight lineSpacing:0];
                    [dicTitleAttr setValue:style forKey:NSParagraphStyleAttributeName];
                    [labelColumn setTextAlignment:NSTextAlignmentRight];
                    sTitle = [Util getCurrencyFromString:sTitle formatter:nil];
                    sTitle = [sTitle stringByAppendingString:@" "];
                }
            }
            NSAttributedString *sAttrString = [[NSAttributedString alloc] initWithString:sTitle attributes:dicTitleAttr];
            [labelColumn setAttributedText:sAttrString];
        }
        xPos += [numberWidth floatValue];
    }
    NSString *sString = [ComUtil getString:sNotiName basic:NSStringFromCGPoint(CGPointZero)];
    CGPoint point = CGPointFromString(sString);
    if ( !CGPointEqualToPoint(point, CGPointZero))
        [cellScrollView setContentOffset:CGPointFromString(sString)];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

//info.m_strSavedDate = [m_tranCondList getDataValue:strBlockName field:@"sDate" index:i];
//info.m_strSavedTime = [m_tranCondList getDataValue:strBlockName field:@"sTime" index:i];
//info.m_strSeqNo = [m_tranCondList getDataValue:strBlockName field:@"lSeq" index:i];
//info.m_strCondName = [m_tranCondList getDataValue:strBlockName field:@"sContName" index:i];
//info.m_strGroupName = [m_tranCondList getDataValue:strBlockName field:@"sGroupName" index:i];
//info.m_strCondDesc = [m_tranCondList getDataValue:strBlockName field:@"sMemo" index:i];

- (void)setSearchItemInfo:(CondSearchInfo*)infoCond
{
    [self setTitleWithTag:100 title:infoCond.m_strSavedDate];
    [self setTitleWithTag:101 title:infoCond.m_strSavedTime];
    [self setTitleWithTag:102 title:infoCond.m_strSeqNo];
    [self setTitleWithTag:103 title:infoCond.m_strCondName];
    [self setTitleWithTag:104 title:infoCond.m_strGroupName];
    [self setTitleWithTag:105 title:infoCond.m_strCondDesc];
    
    [cellScrollView setContentOffset:scrolllPoint];
}


- (void)setItemInfo:(CondItemInfo*)infoCond
{
    [self setTitleWithTag:0 + 100 title:infoCond.m_strItemCode];
    [self setTitleWithTag:1 + 100 title:infoCond.m_strName];
    [self setTitleWithTag:2 + 100 title:infoCond.m_strBasePrice];
    [self setTitleWithTag:3 + 100 title:infoCond.m_strOpenPrice];
    [self setTitleWithTag:4 + 100 title:infoCond.m_strHighPrice];
    [self setTitleWithTag:5 + 100 title:infoCond.m_strLowPrice];
    [self setTitleWithTag:6 + 100 title:infoCond.m_strResult];
    
    [cellScrollView setContentOffset:scrolllPoint];
}

- (void)setTitleWithTag:(NSInteger)nTag title:(NSString*)title{
    UILabel *label = [self.contentView viewWithTag:nTag];
    if ( label != nil){
        [label setText:title];
    }
}

@end
