// // RulesDetailViewController.m // kneet // // Created by Jason Lee on 3/18/15. // Copyright (c) 2015 ntels. All rights reserved. // @import ObjectiveC.runtime; #import "JDObject.h" #import "RequestHandler.h" #import "RuleModel.h" #import "CustomCheckBox.h" #import "CustomLabel.h" #import "CustomImageView.h" #import "CustomAlertView.h" #import "CustomTextView.h" #import "RulesRegisterViewController.h" #import "RulesDetailViewController.h" #import "DeviceModel.h" #import "RulesViewController.h" @implementation RulesDetailTitleViewCell - (void)awakeFromNib { self.backgroundColor = [UIColor clearColor]; } @end @interface RulesDetailTableViewCell () { } @property (weak, nonatomic) ItemModel *item; @end @implementation RulesDetailTableViewCell - (void)awakeFromNib { self.backgroundColor = [UIColor clearColor]; } @end @implementation RulesDetailActivationViewCell - (void)awakeFromNib { self.backgroundColor = [UIColor clearColor]; _lblRunTitle.text = NSLocalizedString(@"규칙 활성화", @"규칙 활성화"); } @end @implementation RulesDetailDisableViewCell - (void)awakeFromNib { self.backgroundColor = [UIColor clearColor]; _lblDesc.text = NSLocalizedString(@"일부 장치 또는 멤버가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요", @"일부 장치 또는 멤버가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요"); } @end @interface RulesDetailViewController () { RuleDetailModel *_ruleDetail; NSInteger _triggerCount, _actionCount, _conditionCount; BOOL _isNotFirstLoading; UIImage *_iconTrigger, *_iconAction; UIImage *_btnRunBgImageNormal, *_btnRunBgImageHighlight; CustomButton *_btnRun; NSMutableArray *_arrayForHeader; BOOL _testToggle; //for debug } @end #pragma mark - Class Definition @implementation RulesDetailViewController - (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; _iconTrigger = [UIImage imageNamed:@"tp_01_img_rule_rbox_icon_trigger"]; _iconAction = [UIImage imageNamed:@"tp_01_img_rule_rbox_icon_action"]; _btnRunBgImageNormal = [UIImage imageNamed:@"tp_01_img_control_switch_onoff_on"]; _btnRunBgImageHighlight = [UIImage imageNamed:@"tp_01_img_control_switch_onoff_off"]; if ([JDFacade facade].loginUser.level <= 10) {//심플멤버일 경우, _constraintActionTabHeight.constant = 0; } //Localization [_btnEdit setTitle:NSLocalizedString(@"편집", @"편집") forState:UIControlStateNormal]; [_btnDelete setTitle:NSLocalizedString(@"삭제", @"삭제") forState:UIControlStateNormal]; } - (void)prepareViewDidLoad { //룰 상세 조회 // [self requestRuleDetail]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.title = NSLocalizedString(@"홈 규칙 상세",nil); [self performSelector:@selector(requestRuleDetail) withObject:nil afterDelay:0.0f]; } #pragma mark - Main Logic - (void)requestRuleDetail { //parameters NSString *path = [NSString stringWithFormat:API_GET_RULE_DETAIL, _rule.homegrpRuleId]; [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[RuleDetailModel class] completion:^(id responseObject) { if (!responseObject) {//응답결과가 잘못되었거나 없을 경우, return; } _ruleDetail = (RuleDetailModel *) responseObject; if (_ruleDetail) {//API 성공 , [self setRuleDetailContents]; } } failure:^(id errorObject) { JDErrorModel *error = (JDErrorModel *)errorObject; [[JDFacade facade] alert:error.errorMessage]; }]; } + (void)cloneSubItemsForItemSubType:(NSArray *)items conditions:(NSArray *)conditions { for (ItemModel *item in items) { if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우, item.predDevices = (NSMutableArray *)[[NSMutableArray alloc] init]; for (ItemSubModel *subItem in item.subItems) { PredefinedDeviceModel *pdevice = [[PredefinedDeviceModel alloc] initWithSubItem:subItem]; [item.predDevices addObject:pdevice]; if ([pdevice isEqual:item.predDevices.firstObject]) { pdevice.conditions = (NSMutableArray *)[[NSMutableArray alloc] initWithArray:conditions]; } } } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우, item.modes = (NSMutableArray *)[[NSMutableArray alloc] init]; for (ItemSubModel *subItem in item.subItems) { ModeModel *mode = [[ModeModel alloc] initWithSubItem:subItem]; [item.modes addObject:mode]; if ([mode isEqual:item.modes.firstObject]) { mode.conditions = (NSMutableArray *)[[NSMutableArray alloc] initWithArray:conditions]; } } } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우, item.pushes = (NSMutableArray *)[[NSMutableArray alloc] initWithArray:item.subItems]; for (ItemSubModel *subItem in item.pushes) { if ([subItem isEqual:item.subItems.firstObject]) { subItem.conditions = (NSMutableArray *)[[NSMutableArray alloc] initWithArray:conditions]; } } } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우, item.timers = (NSMutableArray *)[[NSMutableArray alloc] initWithArray:item.subItems]; for (ItemSubModel *subItem in item.timers) { if ([subItem isEqual:item.subItems.firstObject]) { subItem.conditions = (NSMutableArray *)[[NSMutableArray alloc] initWithArray:conditions]; } } } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우, item.mobileDevices = [(NSMutableArray *)[NSMutableArray alloc] init]; for (ItemSubModel *subItem in item.subItems) { DeviceModel *device = [[DeviceModel alloc] initWithSubItem:subItem]; [item.mobileDevices addObject:device]; if ([device isEqual:item.mobileDevices.firstObject]) { device.conditions = (NSMutableArray *)[[NSMutableArray alloc] initWithArray:conditions]; } } } } } - (void)setRuleDetailContents { _triggerCount = _ruleDetail.triggers && _ruleDetail.triggers.count ? _ruleDetail.triggers.count : 0; _actionCount = _ruleDetail.actions && _ruleDetail.actions.count ? _ruleDetail.actions.count : 0; _conditionCount = _ruleDetail.conditions && _ruleDetail.conditions.count ? _ruleDetail.conditions.count : 0; //트리거에 컨디션을 넣어줘야함. [RulesDetailViewController cloneSubItemsForItemSubType:_ruleDetail.triggers conditions:_ruleDetail.conditions]; [RulesDetailViewController cloneSubItemsForItemSubType:_ruleDetail.actions conditions:nil]; [_tableView reloadData]; } - (void)requestChangeRuleStatus:(NSString *)statusCode { //parameters NSDictionary *parameter = @{@"status_code" : statusCode}; NSString *path = [NSString stringWithFormat:API_POST_RULE_STATUS, _ruleDetail.homegrpRuleId]; [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) { _ruleDetail.useYn = [_ruleDetail.useYn boolValue] ? ksNO : ksYES; //toggle [self changeBtnRunStatus:[_ruleDetail.useYn boolValue]]; [[JDFacade facade] toast:NSLocalizedString(@"변경되었습니다", @"변경되었습니다")]; RulesViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[RulesViewController class]]; [vc updateRule:_ruleDetail]; } failure:^(id errorObject) { JDErrorModel *error = (JDErrorModel *)errorObject; [[JDFacade facade] alert:error.errorMessage]; }]; } - (void)requestDeleteRule { NSString *path = [NSString stringWithFormat:API_DELETE_RULE, _ruleDetail.homegrpRuleId]; [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) { [[JDFacade facade] toast:NSLocalizedString(@"삭제되었습니다", @"삭제되었습니다")]; [[JDFacade facade] gotoWishMenu:KNMenuIdRules]; } failure:^(id errorObject) { JDErrorModel *error = (JDErrorModel *)errorObject; [[JDFacade facade] alert:error.errorMessage]; }]; } #pragma mark - UITableView DataSource & Delegate - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 4 + ([_ruleDetail.useYn isEqualToString:ksKneetRulesDisable] ? 1 : 0); } - (NSString *)titleForSectionHeader:(NSInteger)section { NSString *title = nil; switch (section) { case 1: title = NSLocalizedString(@"언제 실행할까요?", @"언제 실행할까요?"); break; case 2: title = NSLocalizedString(@"무엇을 실행할까요?", @"무엇을 실행할까요?"); break; } return title; } - (UIImage *)imageForSection:(NSInteger)section { UIImage *image = nil; switch (section) { case 1: image = _iconTrigger; break; case 2: image = _iconAction; break; } return image; } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil; if (!view) { RulesCreateHeaderTableViewCell *hcell = (RulesCreateHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"]; CGFloat height = [self tableView:tableView heightForHeaderInSection:section]; hcell.frame = CGRectMake(0, 0, IPHONE_WIDTH, height); if (section == 0) {//titleCell hcell.imgvTop.hidden = YES; hcell.constraintHeaderTitleTop.constant = 10; } view = [[UIView alloc] initWithFrame:hcell.frame]; [view addSubview:hcell]; hcell.lblHeaderTitle.text = [self titleForSectionHeader:section]; [_arrayForHeader insertObject:view atIndex:section]; } return view; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { if (section == 1 || section == 2) {//trigger & actions return 72.0f; } return 0.01f; } - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { return 0.01f; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSInteger count = 1; if (section == 1) {//triggers count = _triggerCount; } else if (section == 2) {//actions count = _actionCount; } return count; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGFloat height = 0; if (indexPath.section == 0) {//title height = 80; } else if (indexPath.section == 1 || indexPath.section == 2) {//triggers & actions //calcualate subItemsText NSArray *items = nil; if (indexPath.section == 1) { items = _ruleDetail.triggers; } else if (indexPath.section == 2) { items = _ruleDetail.actions; } ItemModel *item = items[indexPath.row]; CGFloat adjustHeight = [RulesRegisterViewController heightForSubItems:item isTrigger:indexPath.section == 1]; adjustHeight = adjustHeight > 0 ? adjustHeight + 15 + 20 : adjustHeight; height = 60 + adjustHeight; } else if (indexPath.section == 3) {//activation height = 90.0f; } else if (indexPath.section == 4) {//disable height = 52.0f; } return height; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = nil; if (indexPath.section == 0) { RulesDetailTitleViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"]; if (tcell == nil) { tcell = [[RulesDetailTitleViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TitleCellIdentifier"]; } tcell.lblRuleTitle.text = _ruleDetail.ruleName; tcell.lblRuleOwner.text = [NSString stringWithFormat:@"by %@", _ruleDetail.nickname]; cell = tcell; } else if (indexPath.section == 3) {//액션 셀 RulesDetailActivationViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"ActivationCellIdentifier"]; if (tcell == nil) { tcell = [[RulesDetailActivationViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivationCellIdentifier"]; } tcell.selectionStyle = UITableViewCellSelectionStyleNone; if (!_btnRun) { _btnRun = tcell.btnRun; } [self changeBtnRunStatus:[_ruleDetail.useYn boolValue]]; if (![tcell.btnRun actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) { [tcell.btnRun addTarget:self action:@selector(btnRunRuleTouched:) forControlEvents:UIControlEventTouchUpInside]; } cell = tcell; } else if (indexPath.section == 4) {//disable cell = [tableView dequeueReusableCellWithIdentifier:@"DisableCellIdentifier"]; } else { RulesDetailTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; if (tcell == nil) { tcell = [[RulesDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"]; } NSArray *items = nil; if (indexPath.section == 1) { items = _ruleDetail.triggers; } else if (indexPath.section == 2) { items = _ruleDetail.actions; } ItemModel *item = items[indexPath.row]; [RulesRegisterViewController fillCell:tcell item:item isTrigger:indexPath.section == 1]; tcell.imgvItem.image = [self imageForSection:indexPath.section]; cell = tcell; } cell.selectionStyle = UITableViewCellSelectionStyleNone; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } - (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)changeBtnRunStatus:(BOOL)isRun { if (!isRun) { [_btnRun setTitle:@"Off" forState:UIControlStateNormal]; _btnRun.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0); _btnRun.rectForCapBackground = CGRectMake(40, 0, 0, 30); [_btnRun setBackgroundImage:_btnRunBgImageHighlight forState:UIControlStateNormal]; [_btnRun setBackgroundImage:_btnRunBgImageNormal forState:UIControlStateHighlighted]; } else { [_btnRun setTitle:@"On" forState:UIControlStateNormal]; _btnRun.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0); _btnRun.rectForCapBackground = CGRectMake(30, 0, 0, 40); [_btnRun setBackgroundImage:_btnRunBgImageNormal forState:UIControlStateNormal]; [_btnRun setBackgroundImage:_btnRunBgImageHighlight forState:UIControlStateHighlighted]; } } - (void)btnRunRuleTouched:(id)sender { if ([_ruleDetail.useYn isEqualToString:ksKneetRulesDisable]) { [[JDFacade facade] toast:NSLocalizedString(@"일부 장치 또는 멤버가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요", @"일부 장치 또는 멤버가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요")]; return; } BOOL isRun = [_ruleDetail.useYn boolValue]; [self requestChangeRuleStatus:isRun ? @"03" : @"02"]; // _testToggle = !_testToggle; // if (_testToggle) { // [[LocationHandler handler] checkIn]; // } else { // [[LocationHandler handler] checkOut]; // } } - (void)gotoModifyRule { RulesRegisterViewController *vc = (RulesRegisterViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesRegisterViewController" storyboardName:@"Rules"]; vc.tmpRuleDetail = _ruleDetail; PredefinedRuleDetailModel *tmpRuleDetail = [[PredefinedRuleDetailModel alloc] initWithDictionary: @{@"triggers":@[ @{@"pred_rule_id":@"0", @"pred_item_sequence": @"1", @"item_sub_type_code": ksItemSubTypeCodeTimer, @"item_type_code": @"01", @"item_name":NSLocalizedString(@"특정 시간에", @"특정 시간에")}, @{@"pred_rule_id":@"0", @"pred_item_sequence": @"1", @"item_sub_type_code": ksItemSubTypeCodeGeoFencing, @"item_type_code": @"01", @"item_name":NSLocalizedString(@"귀가 또는 외출 시", @"귀가 또는 외출 시")}, @{@"pred_rule_id":@"0", @"pred_item_sequence": @"1", @"item_sub_type_code": ksItemSubTypeCodeMode, @"item_type_code": @"01", @"item_name":NSLocalizedString(@"홈 모드가 바뀔 때", @"홈 모드가 바뀔 때")}, @{@"pred_rule_id":@"0", @"pred_item_sequence": @"1", @"item_sub_type_code": ksItemSubTypeCodeDevice, @"item_type_code": @"01", @"item_name":NSLocalizedString(@"집에 변화가 일어날 때", @"집에 변화가 일어날 때")} ]} error:nil]; vc.tmpPredRuleDetail = tmpRuleDetail; [self.navigationController pushViewController:vc animated:YES]; } - (IBAction)btnEditTouched:(id)sender { if ([_ruleDetail.useYn isEqualToString:ksKneetRulesDisable]) {//삭제된 장치가 있을 경우, NSMutableString *deletedDevices = [[NSMutableString alloc] init]; for (ItemModel *item in _ruleDetail.actions) { if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우, for (PredefinedDeviceModel *pdevice in item.predDevices) { if ([pdevice.deleteYn boolValue]) {//삭제된 장치를 추가 NSString *prefix = [deletedDevices isEmptyString] ? @"" : @", "; [deletedDevices appendFormat:@"%@%@", prefix, pdevice.deviceName]; } } } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우, for (DeviceModel *device in item.mobileDevices) { if ([device.deleteYn boolValue]) {//삭제된 장치를 추가 NSString *prefix = [deletedDevices isEmptyString] ? @"" : @", "; [deletedDevices appendFormat:@"%@%@(%@)", prefix, device.nickname, device.deviceName]; } } } } for (ItemModel *item in _ruleDetail.actions) { if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우, for (PredefinedDeviceModel *pdevice in item.predDevices) { if ([pdevice.deleteYn boolValue]) {//삭제된 장치를 추가 NSString *prefix = [deletedDevices isEmptyString] ? @"" : @", "; [deletedDevices appendFormat:@"%@%@", prefix, pdevice.deviceName]; } } } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우, for (ItemSubModel *push in item.pushes) { if ([push.deleteYn boolValue]) {//삭제된 장치를 추가 NSString *prefix = [deletedDevices isEmptyString] ? @"" : @", "; [deletedDevices appendFormat:@"%@%@", prefix, push.sourceName]; } } } } NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"삭제된 장치 또는 멤버를 정리 후 진행합니다\n\n%@", @"삭제된 장치 또는 멤버를 정리 후 진행합니다\n\n%@"), deletedDevices]; CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:msg delegate:nil OKButtonTitle:NSLocalizedString(@"확인", @"확인") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")]; [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) { if (buttonIndex == 0) {//OK [self gotoModifyRule]; } }]; return; } [self gotoModifyRule]; } - (IBAction)btnDeleteTouched:(id)sender { NSString *messge = NSLocalizedString(@"삭제하시겠습니까?", @"삭제하시겠습니까?"); CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:messge delegate:self OKButtonTitle:NSLocalizedString(@"삭제", @"삭제") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")]; [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) { if (buttonIndex == 0) { [self requestDeleteRule]; } }]; } #pragma mark - MemoryWarning - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end