// // RulesViewController.m // kneet // // Created by Jason Lee on 3/18/15. // Copyright (c) 2015 ntels. All rights reserved. // #import "JDObject.h" #import "RequestHandler.h" #import "RuleModel.h" #import "CustomTableView.h" #import "CustomLabel.h" #import "CustomImageView.h" #import "JYRefreshController.h" #import "UIImageView+WebCache.h" #import "ImageUtil.h" #import "RulesViewController.h" #import "CustomCheckBox.h" #import "RulesDetailViewController.h" #import "RulesAddViewController.h" #define kfRulesTableViewCellHeight 100.0f @implementation RulesTableViewCell @end @interface RulesViewController () { NSMutableArray *_ruleList; NSString *_pagingType, *_pagingId; UIImage *_stateImageRun, *_stateImageStop, *_stateImageDisable; BOOL _isNotFirstLoading, _isDeleteMode; } @property (strong, nonatomic) JYPullToRefreshController *refreshController; @property (strong, nonatomic) JYPullToLoadMoreController *loadMoreController; @end #pragma mark - Class Definition @implementation RulesViewController - (void)viewDidLoad { [super viewDidLoad]; _ruleList = (NSMutableArray *)[[NSMutableArray alloc] init]; [self initUI]; [self prepareViewDidLoad]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)initUI { //initialize tableview [self initTableViewAsDefaultStyle:_tableView]; //set refresh controls // __weak typeof(self) weakSelf = self; // self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.tableView]; // self.refreshController.pullToRefreshHandleAction = ^{ // [weakSelf requestRuleListRecently]; // }; // // self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView]; // self.loadMoreController.pullToLoadMoreHandleAction = ^{ // [weakSelf requestRuleListOlder]; // }; //FIXME : delete? _stateImageRun = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_play"]; _stateImageStop = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_stop"]; _stateImageDisable = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_disable"]; [self setThingsPopoverOptions]; } - (void)setThingsPopoverOptions { //set Popover Contents __weak typeof(self) weakSelf = self; _popooverOptionArray = [[NSMutableArray alloc] init]; [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로 고침",nil), @"iconName": @"tp_01_img_bg_morepopup_icon_refresh", @"target": weakSelf, @"selector": [NSValue valueWithPointer:@selector(refreshRuleList)]}]; if ([JDFacade facade].loginUser.level > 10) {//파워유저 이상일 경우, [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"만들기", @"만들기"), @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd", @"target": weakSelf, @"selector": [NSValue valueWithPointer:@selector(addNewRule)]}]; [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"), @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd", @"target": weakSelf, @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}]; } } - (void)prepareViewDidLoad { if (_ruleList && _ruleList.count) { [_ruleList removeAllObjects]; } [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f]; } - (void)updateHomeHubStatusToRules { [self updateTitle]; } - (void)refreshRuleList { _pagingId = nil; _pagingType = nil; if (_ruleList && _ruleList.count) { [_ruleList removeAllObjects]; } [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f]; } - (void)addNewRule { UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddViewController" storyboardName:@"Rules"]; [self presentViewController:vc animated:YES completion:nil]; } - (void)toggleEditMode { _isDeleteMode = !_isDeleteMode; [_tableView reloadData]; _constraintEditModeRight.constant = _isDeleteMode ? 0 : -_editModeView.width; [UIView animateWithDuration:kfAnimationDur animations:^{ [self.view layoutIfNeeded]; }]; } #pragma mark - Main Logic - (void)requestRuleListRecently { RuleModel *firstRule = [_ruleList firstObject]; _pagingType = ksListPagingTypeUpward; _pagingId = firstRule.ruleId; [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f]; } - (void)requestRuleListOlder { RuleModel *lastRule = [_ruleList lastObject]; _pagingType = ksListPagingTypeDownward; _pagingId = lastRule.ruleId; [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f]; } - (void)requestRules { NSDictionary *parameter = @{@"rule_id": _pagingId ? _pagingId : ksEmptyString, @"paging_type": _pagingType ? _pagingType : ksEmptyString}; NSString *path = [NSString stringWithFormat:API_GET_RULE]; [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[RuleListModel class] completion:^(id responseObject) { if (!responseObject) {//응답결과가 잘못되었거나 없을 경우, return; } RuleListModel *fetchedRuleList = (RuleListModel *)responseObject; if (fetchedRuleList && fetchedRuleList.rules && fetchedRuleList.rules.count) {//API 성공, if (_pagingType && [_pagingType isEqualToString:ksListPagingTypeUpward]) { if (_ruleList.count) { NSRange range = NSMakeRange(0, fetchedRuleList.rules.count); NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range]; [_ruleList insertObjects:fetchedRuleList.rules atIndexes:indexSet]; } else { [_ruleList addObjectsFromArray:fetchedRuleList.rules]; } } else { [_ruleList addObjectsFromArray:fetchedRuleList.rules]; } [self updateTitle]; } else {//실패 시, if (!_ruleList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음. // NoContentView *noContentView = [NoContentView viewFromNib]; // _tableView.tableFooterView = noContentView; } } // [self.refreshController stopRefreshWithAnimated:YES completion:nil]; // [self.loadMoreController stopLoadMoreCompletion:nil]; // self.loadMoreController.enable = _ruleList.count % kdListPagginSize == 0; [_tableView reloadData]; } failure:^(id errorObject) { JDErrorModel *error = (JDErrorModel *)errorObject; [[JDFacade facade] alert:error.errorMessage]; }]; } - (void)requestChangeRuleStatus:(RuleModel *)rule { //parameters NSDictionary *parameter = @{@"status_code" : [rule.useYn isEqualToString:@"Y"] ? @"03" : @"02"}; NSString *path = [NSString stringWithFormat:API_POST_RULE_STATUS, rule.homegrpRuleId]; [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) { rule.useYn = [rule.useYn boolValue] ? ksNO : ksYES; //toggle if ([rule.useYn boolValue]) { [[JDFacade facade] toast:@"규칙을 다시 시작합니다"]; } else { [[JDFacade facade] toast:@"규칙을 중단합니다"]; } // [self changeBtnRunStatus:[rule.useYn boolValue]]; [self updateTitle]; [_tableView reloadData]; } failure:^(id errorObject) { JDErrorModel *error = (JDErrorModel *)errorObject; [[JDFacade facade] alert:error.errorMessage]; }]; } - (void)requestDeleteRule:(RuleModel *)rule { NSString *path = [NSString stringWithFormat:API_DELETE_RULE, rule.homegrpRuleId]; [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) { [[JDFacade facade] toast:@"규칙을 삭제했습니다"]; [_ruleList removeObject:rule]; [self toggleEditMode]; [self updateTitle]; [_tableView reloadData]; } failure:^(id errorObject) { JDErrorModel *error = (JDErrorModel *)errorObject; [[JDFacade facade] alert:error.errorMessage]; }]; } - (void)updateRule:(RuleModel *)rule { for (RuleModel *tmpRule in _ruleList) { if ([rule.homegrpRuleId isEqualToString:tmpRule.homegrpRuleId]) { tmpRule.ruleName = rule.ruleName; tmpRule.useYn = rule.useYn; break; } } [_tableView reloadData]; } - (void)updateTitle { if (![JDFacade facade].loginUser.isHomehubOnline) { _lblTitle.text = @"홈허브 오프라인"; [_lblTitle setColor:kUITextColor02 text:_lblTitle.text]; return; } //활성/비활성 업데이트 NSInteger inactiveCount = [_ruleList filteredArrayUsingPredicateFormat:@"SELF.useYn == %@", ksNO].count; NSInteger activeCount = _ruleList.count > inactiveCount ? _ruleList.count - inactiveCount : inactiveCount - _ruleList.count; _lblTitle.text = [NSString stringWithFormat:@"활성 %zd / 비활성 %zd", activeCount, inactiveCount]; [_lblTitle setColor:kUITextColor02 text:[NSString stringWithFormat:@"%zd", activeCount]]; [_lblTitle setColor:kUITextColor02 text:[NSString stringWithFormat:@"%zd", inactiveCount]]; } #pragma mark - UITableView DataSource & Delegate - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _ruleList.count; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGFloat height = kfRulesTableViewCellHeight; if (indexPath.row == _ruleList.count) { height = _ruleList.count ? 190.0f : IPHONE_HEIGHT - kfNavigationBarHeight; _tableView.scrollEnabled = _ruleList.count; } return height; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { RulesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; RuleModel *rule = _ruleList[indexPath.row]; [cell.imgvTrigger sd_setImageWithURL:[NSURL URLWithString:rule.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached]; cell.lblRuleName.text = rule.ruleName; cell.btnRulePlay.hidden = _isDeleteMode; if (!cell.btnRulePlay.hidden) { cell.btnRulePlay.hidden = [JDFacade facade].loginUser.level < 90; cell.btnDelete.hidden = YES; cell.btnRulePlay.value = rule; if (![cell.btnRulePlay actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) { [cell.btnRulePlay addTarget:self action:@selector(btnRulePlayTouched:) forControlEvents:UIControlEventTouchUpInside]; } } else { cell.btnDelete.hidden = NO; cell.btnDelete.value = rule; if (![cell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) { [cell.btnDelete addTarget:self action:@selector(btnDeleteTouched:) forControlEvents:UIControlEventTouchUpInside]; } } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; if (indexPath.row == _ruleList.count) { return; } if (!_isDeleteMode) {//go to detail //goto rule details RulesDetailViewController *vc = (RulesDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesDetailViewController" storyboardName:@"Rules"]; vc.refRule = _ruleList[indexPath.row]; [self presentViewController:vc animated:YES completion:nil]; } } #pragma mark - TableView UI Events - (void)btnRulePlayTouched:(id)sender { CustomButton *btnRulePlay = (CustomButton *)sender; RuleModel *rule = btnRulePlay.value; if ([rule.useYn isEqualToString:ksKneetRulesDisable]) { CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:@"일부 장치가 삭제되었습니다.\n편집 후 실행하세요." delegate:nil OKButtonTitle:@"편집" cancelButtonTitle:@"취소"]; [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) { if (buttonIndex == 0) {//OK dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread NSString *path = [NSString stringWithFormat:API_GET_RULE_DETAIL, rule.homegrpRuleId]; RuleDetailModel *ruleDetail = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil modelClass:[RuleDetailModel class] showLoadingView:YES]; RulesAddViewController *vc = (RulesAddViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddViewController" storyboardName:@"Rules"]; vc.refRuleDetail = ruleDetail; dispatch_async(dispatch_get_main_queue(), ^{ [self presentViewController:vc animated:YES completion:nil]; }); }); } }]; return; } [self requestChangeRuleStatus:rule]; } - (void)btnDeleteTouched:(id)sender { [[JDFacade facade] confirmTitle:@"규칙 삭제" message:@"규칙을 삭제하시겠습니까?" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) { if (buttonIndex == 0) {//OK CustomButton *btnDelete = (CustomButton *)sender; RuleModel *rule = btnDelete.value; [self requestDeleteRule:rule]; } }]; } #pragma mark - UI Events - (IBAction)btnOptionTouched:(id)sender { [self toggleOptions:sender]; } - (IBAction)btnCloseOnEditModeTouched:(id)sender { [self toggleEditMode]; } #pragma mark - MemoryWarning - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end