//
//  RegisterPushViewController.m
//  kneet
//
//  Created by Jason Lee on 5/26/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "RequestHandler.h"
#import "RuleModel.h"

#import "CustomTextView.h"
#import "CustomLabel.h"
#import "CustomRadioGroup.h"
#import "CustomCheckBox.h"

#import "ScenesRegisterViewController.h"
#import "RulesRegisterViewController.h"
#import "PredefinedDeviceViewController.h"

#import "RegisterPushViewController.h"
#import "CustomButton.h"
#import "ImageUtil.h"

@implementation RegisterPushTableViewCell
- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    _txvMessage.placeHolder = NSLocalizedString(@"여기에 푸시알림으로 받고 싶은 메시지를 입력하세요", @"여기에 푸시알림으로 받고 싶은 메시지를 입력하세요");
}
@end

@implementation RegisterPushMemberTableViewCell
- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}
@end

@implementation RegisterPushMemberTitleViewCell
- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [_btnPushMemberTitle setTitle:NSLocalizedString(@"푸시 받을 멤버", @"푸시 받을 멤버") forState:UIControlStateNormal];
}

@end

@implementation RegisterPushMethodTableViewCell
- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [_btnMethodTitle setTitle:NSLocalizedString(@"푸시 방법", @"푸시 방법") forState:UIControlStateNormal];
    [_rdoNotificationCenter setTitle:NSLocalizedString(@"알림센터", @"알림센터") forState:UIControlStateNormal];
    [_rdoPopup setTitle:NSLocalizedString(@"팝업알림", @"팝업알림") forState:UIControlStateNormal];
    
    _lblMethodDesc.text = NSLocalizedString(@"아이폰을 사용하는 멤버는 휴대폰 설정의\n알림센터에서 지정한 방식에 따라 푸시를 받게됩니다", @"아이폰을 사용하는 멤버는 휴대폰 설정의\n알림센터에서 지정한 방식에 따라 푸시를 받게됩니다");
}
@end

@interface RegisterPushViewController () <UITableViewDataSource, UITableViewDelegate, CustomCheckBoxDelegate> {
    CustomTextView *_txvTextView;
    NSArray<RulePushMemberModel> *_pushMemberList;
    CustomRadioGroup *_rgroup;
    UIImage *_bgCellImage1, *_bgCellImage2;
    BOOL _isNotFirstLoading;
}
@end


#pragma mark - Class Definition

@implementation RegisterPushViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    
    

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

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

    _tableView.tableFooterView = [[UIView alloc] init]; //this call table events;
    
    _rgroup = [[CustomRadioGroup alloc] init];
    
    UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
    _bgCellImage1 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
    _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
    
    //Localization
    [_btnSelect setTitle:NSLocalizedString(@"입력완료", @"입력완료") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {
    [self performSelector:@selector(requestMembersForPush) withObject:nil afterDelay:0.0f];
}

#pragma mark - Main Logic
- (void)requestMembersForPush {
    //parameters
    NSString *path = [NSString stringWithFormat:API_GET_RULE_MEMBERS];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[RulePushMemberListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        RulePushMemberListModel *fetchedPushMemberList = (RulePushMemberListModel *) responseObject;
        
        if (fetchedPushMemberList && fetchedPushMemberList.list && fetchedPushMemberList.list.count) {//API 성공 ,
            _pushMemberList = fetchedPushMemberList.list;
        }
        [self matchPushMemberList];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)matchPushMemberList {
    
    for (ItemSubModel *subItem in _tmpItem.pushes) {//이전에 선택된 멤버를 다시 선택해줌.
        NSInteger idx = [_pushMemberList indexOfObjectPassingTest:^BOOL(RulePushMemberModel *pmember, NSUInteger idx, BOOL *stop) {
            return [subItem.sourceId isEqualToString:pmember.memberId];
        }];
        
        if (idx != NSNotFound) {
            RulePushMemberModel *pmember = _pushMemberList[idx];
            [[JDFacade facade] setCheckBoxStatus:@YES object:pmember];  //for checkbox
        }
    }

    [_tableView reloadData];
}


#pragma mark - UITableView DataSource & Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2 + (_pushMemberList && _pushMemberList.count ? 3 : 0);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 1;
    if (section == 4) {//push members
        count = _pushMemberList.count;
    }

    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0) {//title
        height = 88;
    } else if (indexPath.section == 1) {//devices
        height = 185;
    } else if (indexPath.section == 2) {//push method
        height = 145;
    } else if (indexPath.section == 3) {//push title
        height = 30;
    } else if (indexPath.section == 4) {//push members
        height = 60;
    }

    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {//title
        RulesDeviceTitleViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        if (tcell == nil) {
            tcell = [[RulesDeviceTitleViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TitleCellIdentifier"];
        }
        
        [tcell.btnActionTitle setTitle:NSLocalizedString(@"푸시알림", @"푸시알림") forState:UIControlStateNormal];
        tcell.lblSelectCount.text = [NSString stringWithFormat:@"%zd / %zd", [self countForCheckedMembers], _pushMemberList.count];

        cell = tcell;

    } else if (indexPath.section == 1) {//predefined device list
        RegisterPushTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"MessageCellIdentifier"];

        if (tcell == nil) {
            tcell = [[RegisterPushTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MessageCellIdentifier"];
        }

        if (!_txvTextView) {
            _txvTextView = tcell.txvMessage;

            if (_tmpItem.pushes && _tmpItem.pushes.count) {
                ItemSubModel *push = _tmpItem.pushes[0];
                _txvTextView.text = push.cmdclsValue;
            }
        }

        cell = tcell;
    } else if (indexPath.section == 2) {//push method
        RegisterPushMethodTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"MethodCellIdentifier"];
        
        if (!_rgroup.rdoBtns.count) {
            
            tcell.rdoNotificationCenter.value = @"01";
            tcell.rdoPopup.value = @"02";
            
            [_rgroup addRadioButton:tcell.rdoNotificationCenter];
            [_rgroup addRadioButton:tcell.rdoPopup];            
            if (_tmpItem.pushes && _tmpItem.pushes.count) {
                ItemSubModel *push = _tmpItem.pushes[0];
                
                if ([push.conditionTypeCode isEqualToString:@"02"]) {
                    [_rgroup someRadioButtonTouched:tcell.rdoPopup];
                }
            }
            
        }
        
        cell = tcell;
    } else if (indexPath.section == 3) {//push title
        RegisterPushMemberTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"PushTitleCellIdentifier"];
        cell = tcell;
    } else if (indexPath.section == 4) {//push members
        RegisterPushMemberTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"PushMemberCellIdentifier"];
        
        RulePushMemberModel *pmember = _pushMemberList[indexPath.row];
        tcell.lblMemberName.text = pmember.nickname;
        tcell.chkSelect.value = pmember;
        tcell.chkSelect.delegate = self;
        tcell.chkSelect.checked = [tcell.chkSelect getCheckStatusFromValue];
        
        cell = tcell;
        
        //set background image
        if (indexPath.row % 2 == 1) {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage1];
        } else {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage2];
        }
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 4) {//액션일 경우,
        
        RegisterPushMemberTableViewCell *tcell = (RegisterPushMemberTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        [tcell.chkSelect checkBoxClicked];   
        [_tableView reloadData];
    }
}


- (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 - CustomCheckBox Delegate
- (NSInteger)countForCheckedMembers {
    NSInteger count = 0;
    for (RulePushMemberModel *pmember  in _pushMemberList) {
        if ([[[JDFacade facade] getCheckBoxStatus:pmember] boolValue]) {
            count++;
        }
    }
    return count;
}


- (void)didCheckBoxClicked:(id)sender {
//    CustomCheckBox *chk = (CustomCheckBox *)sender;
//    RulePushMemberModel *pmember = chk.value;
    
    [_tableView reloadData];
}


#pragma mark - UI Events
- (void)btnSelectTouched:(id)sender {
    //1.validate
    if (!_txvTextView.text || [_txvTextView.text isEmptyString] || [_txvTextView.text isEqualToString:_txvTextView.placeHolder]) {
        [[JDFacade facade] alert:NSLocalizedString(@"푸시내용을 입력해주세요", @"푸시내용을 입력해주세요")];
        return;
    }
    
    _tmpItem.pushes = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] init];
    
    for (RulePushMemberModel *pmember in _pushMemberList) {
        if ([[[JDFacade facade] getCheckBoxStatus:pmember] boolValue]) {
            
            ItemSubModel *subItem = [[ItemSubModel alloc] init];
            subItem.cmdclsValue = _txvTextView.text;
            subItem.sourceId = pmember.memberId;
            subItem.sourceName = pmember.nickname;
            subItem.conditionTypeCode = _rgroup.valueForChecked;
            
            [_tmpItem.pushes addObject:subItem];
        }
    }
    
    if (!_tmpItem.pushes.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"선택된 멤버가 없습니다", @"선택된 멤버가 없습니다")];
        return;
    }
    
    if (_isCustomCreation) {//자유 선택
        if (_tmpItem.predSceneId && ![_tmpItem.predSceneId isEmptyString]) {//씬일 경우,
            ScenesRegisterViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ScenesRegisterViewController class]];
            [vc addItem:_tmpItem];
        } else if (_tmpItem.predRuleId && ![_tmpItem.predRuleId isEmptyString]) {//룰일 경우,
            RulesRegisterViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[RulesRegisterViewController class]];
            [vc addItem:_tmpItem];
        }
    }

    //    [[JDFacade facade] toast:@"추가되었습니다."];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)btnCancelTouched:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - MemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
