//
//  ModePopTableView.m
//  kneet
//
//  Created by Jason Lee on 4/27/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "ModeModel.h"

#import "CustomLabel.h"
#import "CustomImageView.h"
#import "CustomCheckBox.h"
#import "UIImageView+WebCache.h"

#import "ModePopTableView.h"
#import "RequestHandler.h"
#import "ItemModel.h"
#import "ImageUtil.h"

#define kfModePopTableViewCellHeight 100.0f

@interface ModePopTableViewCell : UITableViewCell

@property (strong, nonatomic) CustomImageView *imgvImage;
@property (strong, nonatomic) CustomLabel *lblTitle;
@property (strong, nonatomic) CustomCheckBox *chkSelect;

@end

@implementation ModePopTableViewCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        self.imgvImage = [[CustomImageView alloc] initWithFrame:CGRectMake(10, 20, 60, 60)];
        _imgvImage.contentMode = UIViewContentModeScaleAspectFit;


        CGFloat width = IPHONE_WIDTH - 80 - 25 - 10 - 20 - 20; //margin - margin - radiosize - padding
        self.lblTitle = [[CustomLabel alloc] initWithFrame:CGRectMake(80, 20, width, 60)];
        _lblTitle.numberOfLines = 0;
        _lblTitle.font = [UIFont systemFontOfSize:kUIFontSize02];
        _lblTitle.textColor = kUITextColor01;


        self.chkSelect = [[CustomCheckBox alloc] initWithFrame:CGRectMake(80 + width + 10, 37.5, 25.0f, 25.0f) normalImage:[UIImage imageNamed:@"common_checkbox_default"] highlightImage:[UIImage imageNamed:@"common_checkbox_checked"]];

        [self addSubview:_imgvImage];
        [self addSubview:_lblTitle];
        [self addSubview:_chkSelect];

        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}



@end

@interface ModePopTableView () <UITableViewDataSource, UITableViewDelegate> {
    UIImage *_bgCellImage;
    BOOL _isNotFirstLoading;
    ItemSubModel *_subCondition;
    NSMutableArray<ModeModel> *_modeList;
}

@end

@implementation ModePopTableView
@synthesize condition = _condition;

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"ModePopTableView"]) {
        if ([view isKindOfClass:[ModePopTableView class]]) {
            self = (ModePopTableView *)view;

            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;

            self.lblTitle.text = NSLocalizedString(@"이 홈모드에서만 실행",nil);

            _tableView.dataSource = self;
            _tableView.delegate = self;

            _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            _tableView.backgroundColor = [UIColor clearColor];
            _tableView.scrollEnabled = YES;

            _tableView.tableFooterView = [[UIView alloc] init];


            UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
            _bgCellImage = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
            
            [self.btnConfirm setTitle:NSLocalizedString(@"선택", @"선택") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

- (void)didMoveToSuperview {
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (!newSuperview)
        return;

    [self loadData];
}

- (void)loadData {
    [self requestModes];
}

- (void)requestModes {
    NSString *path = API_GET_DASHBOARD_MODE_LIST;

    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[ModeListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        ModeListModel *fetchedModeList = (ModeListModel *)responseObject;

        if (fetchedModeList && fetchedModeList.list && fetchedModeList.list.count) {//API 성공 ,
            _modeList = (NSMutableArray<ModeModel> *)[[NSMutableArray alloc] initWithArray:fetchedModeList.list];

            if (_subCondition && _subCondition.cmdclsValue) {//match the previous select

                NSArray *tmpList = [_subCondition.cmdclsValue componentsSeparatedByString:@","];
                for (NSString *modeId in tmpList) {
                    NSInteger indx = [_modeList indexOfObjectPassingTest:^BOOL(ModeModel *obj, NSUInteger idx, BOOL *stop) {//일치하는 인덱스를 구함.
                        return [modeId isEqualToString:obj.modeId];
                    }];

                    if (indx != NSNotFound)  {
                        ModeModel *mode = _modeList[indx];
                        [[JDFacade facade] setCheckBoxStatus:@YES object:mode];  //for check box
                    }
                }
            }

            [self setModeContents];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)setModeContents {
    [_tableView reloadData];
}


#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _modeList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CellIdentifier";

    ModePopTableViewCell *cell = (ModePopTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[ModePopTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    ModeModel *mode = _modeList[indexPath.row];

    cell.lblTitle.text = mode.modeName;
    cell.chkSelect.value = mode;
    [cell.imgvImage sd_setImageWithURL:[NSURL URLWithString:mode.imageFileName] placeholderImage:nil];
    cell.chkSelect.checked = [cell.chkSelect getCheckStatusFromValue];

    cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    ModeModel *mode = _modeList[indexPath.row];
    ModePopTableViewCell *tcell = (ModePopTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    tcell.chkSelect.value = mode;
    [tcell.chkSelect checkBoxClicked];

    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - UI Events
- (void)didCheckBoxClicked:(id)sender {
//    CustomCheckBox *chk = (CustomCheckBox *)sender;
//    ModeModel *mode = chk.value;
}

- (NSString *)homeModes {
    NSMutableString *modeString = [[NSMutableString alloc] init];

    for (ModeModel *mode  in _modeList) {
        if ([[[JDFacade facade] getCheckBoxStatus:mode] boolValue]) {
            NSString *prefix = [modeString isEmptyString] ? ksEmptyString : @", ";
            [modeString appendFormat:@"%@%@", prefix, mode.modeName];
        }
    }
    return modeString;
}

- (NSString *)homeModesCommandClassValue {
    NSMutableString *modeString = [[NSMutableString alloc] init];

    for (ModeModel *mode  in _modeList) {
        if ([[[JDFacade facade] getCheckBoxStatus:mode] boolValue]) {
            NSString *prefix = [modeString isEmptyString] ? ksEmptyString : @",";
            [modeString appendFormat:@"%@%@", prefix, mode.modeId];
        }
    }
    return modeString;
}

- (void)setCondition:(ItemModel *)condition {

    _condition = condition;

    if (!_condition) {
        _condition = [[ItemModel alloc] init];
        _condition.itemName = NSLocalizedString(@"홈모드", @"홈모드");
        _condition.itemSubTypeCode = ksConditionSubTypeCodeHomeMode;
    }

    if (_condition.subItems && _condition.subItems.count) {
        _subCondition = _condition.subItems[0];
    } else {
        _subCondition = [[ItemSubModel alloc] init];
        _subCondition.sourceId = @"VAR";
        _subCondition.conditionTypeCode = @"01";
        _condition.subItems = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithObjects:_subCondition, nil];
    }
}

- (ItemModel *)condition {

    //validate
    if (![self validateCondition]) {
        return nil;
    }

    _subCondition.cmdclsValue = [self homeModesCommandClassValue];
    _subCondition.homeModes = [self homeModes];
    return _condition;
}

- (BOOL)validateCondition {
    NSInteger count = 0;
    for (ModeModel *mode  in _modeList) {
        if ([[[JDFacade facade] getCheckBoxStatus:mode] boolValue]) {
            count ++;
        }
    }

    //1. validate
    if (count == 0) {
        [[JDFacade facade] alert:NSLocalizedString(@"홈모드를 선택해주세요", @"홈모드를 선택해주세요")];
    }
    return count;
}

- (void)btnConfirmTouched:(id)sender {

    //validate
    if (![self validateCondition]) {
        return;
    }

    [super btnConfirmTouched:sender];
}

@end
