//
//  ManagementViewController.m
//  OneCable
//
//  Created by nComz on 2017. 4. 12..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "JDObject.h"
#import "RequestHandler.h"
#import "CustomLabelButton.h"
#import "ImageUtil.h"
#import "HomeModeUpdateViewController.h"
#import "HomeModeSettingsViewController.h"
#import "PwdPopupView.h"
#import "MainViewController.h"
#import "ManagementViewController.h"
#import "SettingsViewController.h"
#import "MultiHomeHubViewController.h"
#import "UIImageView+WebCache.h"

/**
 모드 버튼 Bg Image
 on : common_homemode_icon_bg_on
 off : common_homemode_icon_bg_off
 
 모드 버튼 Icon Image
 기상 : common_homemode_icon_wakeup_on , _off
 외출 : common_homemode_icon_outing_on , _off
 귀가 : common_homemode_icon_homecoming_on , _off
 취침 : common_homemode_icon_sleep_on , _off
 **/
@interface ManagementViewController ()
{
    DashboardModel *_dashboard;
    BOOL _isNotFirstLoading;
}

@end

@implementation ManagementViewController

- (void)viewDidLoad {
    
    for (CustomImageView * imgvCheck in _imgvChecked) {
        imgvCheck.hidden = YES;
    }
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [super viewDidLoad];
}


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


- (void)updateHomeHubStatusToManage {
    [self setContents];
}

- (void)viewWillAppear:(BOOL)animated {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    statusBar.backgroundColor = [UIColor clearColor];
    
    [self requestDashboard:nil];
}

// 공지사항 이동
- (IBAction)btnNoticeTouched:(id)sender {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"NoticeViewController" storyboardName:@"Main"];
    [self presentViewController:vc animated:YES completion:nil];
}

// 자주 찾는 질문 이동
- (IBAction)btnFaqTouched:(id)sender {
    
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"FaqViewController" storyboardName:@"Main"];

    UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:m_navi animated:YES completion:nil];
}

// 메시지 박스 이동
- (IBAction)btnMessageBoxTouched:(id)sender {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MessageBoxViewController" storyboardName:@"Main"];
    [self presentViewController:vc animated:YES completion:nil];
}

// 홈허브 이동
- (IBAction)btnHomeHubTouched:(id)sender {

    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubViewController" storyboardName:@"Main"];
    
    //멀티 홈허브일때
    if ([[JDFacade facade].loginUser isMultiHomeHub]) {
    
        vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MultiHomeHubViewController" storyboardName:@"Main"];
    }
    
    UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:m_navi animated:YES completion:nil];
}

// 설정 이동
- (IBAction)btnSettingsTouched:(id)sender {
    
    //    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SettingsViewController" storyboardName:@"Settings"];
    
    SettingsViewController *settingsVc =[CommonUtil instantiateViewControllerWithIdentifier:@"SettingsViewController" storyboardName:@"Settings"];
    
    settingsVc.dashboardModel = _dashboard;
    
    UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:settingsVc];
    
    [self presentViewController:m_navi animated:YES completion:nil];
}

- (IBAction)btnModeMorningTouched:(id)sender {
    [self doChangeHomeMode:HOME_MODE_MORNING];
}

- (IBAction)btnModeAwayTouched:(id)sender {
    [self doChangeHomeMode:HOME_MODE_AWAY];
}

- (IBAction)btnModeHomeTouched:(id)sender {
    [self doChangeHomeMode:HOME_MODE_HOME];
}

- (IBAction)btnModeNightTouched:(id)sender {
    [self doChangeHomeMode:HOME_MODE_NIGHT];
}

//- (void)modeBtnOn:(CustomImageView *)imgvOn {
//
//    for (CustomImageView *imgvMode in _imgvModes) {
//        if ([imgvMode isEqual:imgvOn]) {
//            [imgvMode setHighlighted:YES];
//        } else {
//            [imgvMode setHighlighted:NO];
//        }
//    }
//}
//
//- (void)modeBtnCheck:(CustomImageView *)imgvCheck {
//
//    for (CustomImageView *imgvChecked in _imgvChecked) {
//        if ([imgvChecked isEqual:imgvCheck]) {
//            [imgvChecked setHidden:NO];
//        } else {
//            [imgvChecked setHidden:YES];
//        }
//    }
//}

//- (IBAction)btnDashboardRefresh:(id)sender {
//    [self requestDashboard:nil];
//}

- (void)requestDashboard:(JDFacadeCompletionCallBackHandler)completion {
    //parameters
    NSDictionary *parameter = @{@"member_id": [JDFacade facade].loginUser.memberId,
                                @"notice_read_datetime": [JDFacade facade].loginUser.noticeReadTime ? [JDFacade facade].loginUser.noticeReadTime : ksEmptyString,
                                @"message_read_datetime": [JDFacade facade].loginUser.personalNoticeReadTime ? [JDFacade facade].loginUser.personalNoticeReadTime : ksEmptyString};
    
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_POST_DASHBOARD arguments:nil];
    //    NSString *path = [NSString stringWithFormat:API_GET_DASHBOARD, [[JDFacade facade].loginUser custId], [[JDFacade facade].loginUser ctrtGrpId]];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[DashboardModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DashboardModel *dashboard = (DashboardModel *) responseObject;
        //        NSLog(@"DashBoard Info : %@", responseObject);

        NSLog(@"DashBoard Info : %@", dashboard.modeList);
        if (dashboard) {//API 성공 ,
            _dashboard = dashboard;
            
            
            //            if (!_isNotFirstLoading) {
            //                _isNotFirstLoading = YES;
            // FIXME : 이부분이 어떤 내용인지 파악해야 한다.
            //                [JDFacade facade].loginUser.homehubDeviceId = _dashboard.deviceId; //초대에서 넘어오는 경우,
            
            //                when first loading this view.
            //                [self initThingsViewController];
            //
            //                self.currentChildViewController = _tvc;
            //                [_btnThings setHighlighted:YES];
            //            }
            
            [self setContents];
        }
        
        if (completion) {
            completion();
        }
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


//extendView 컨텐츠 설정
- (void)setContents {
    
    NSLog(@"setcontent : %@",_dashboard);
    
    _imgNoticeCount.hidden = _lblNoticeCount.hidden = EQUALS(_dashboard.noticeCount, @"0");
    _imgPushCount.hidden = _lblPushCount.hidden = EQUALS(_dashboard.pushCount, @"0");
    
    _lblNoticeCount.text = _dashboard.noticeCount;
    _lblPushCount.text = _dashboard.pushCount;

    [_imgvLogo sd_setImageWithURL:[NSURL URLWithString:[JDFacade facade].loginUser.msoImageUrl] placeholderImage:nil options:SDWebImageRefreshCached];
    
    //    _imgvHomehubOff.hidden = [JDFacade facade].loginUser.isHomehubOnline;
    
    
    _imgvHomehubOff.hidden = ![_dashboard.deviceEventYn boolValue];
    _imgvSetAlert.hidden = [_dashboard.phoneAuthYn boolValue];
    
    
    //    _btnHomeHub.enabled = [JDFacade facade].loginUser.hasHomeHub;
    //    _btnHomeHub.alpha = _btnHomeHub.enabled ? 1.0f : 0.4f;
    
    //don't delete - FOR KNEET2.0
    //    [_btnHomegrpImage sd_setImageWithURL:[NSURL URLWithString:_dashboard.imageFileName] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
    
    NSInteger i = 0;
    for (ModeModel *mode in _dashboard.modeList) {//모드버튼 설정
        CustomLabelButton *btn = _btnModes[i];
        [btn setTitle:mode.modeName];

        if (![JDFacade facade].loginUser.hasHomeHub) {//비활성모드 : 홈허브가 없을 경우, 또는 삭제된 경우,
            [btn sd_setImageWithURL:[NSURL URLWithString:mode.imageFileDisableName] forState:UIControlStateNormal];
            //            btn.label.textColor = kUITextColor04;
            //            btn.label.alpha = 0.4f;
            btn.enabled = NO;
            btn.imgvMode.highlighted = NO;
            btn.imgvBtnBg.highlighted = NO;
            btn.imgvCheck.hidden = YES;
        } else {
            
            if ([mode.useYn boolValue]) {//활성모드
                //                [btn sd_setImageWithURL:[NSURL URLWithString:mode.imageFileActiveName] forState:UIControlStateNormal];
                //                btn.label.textColor = kUITextColor01;
                //                btn.label.alpha = 1.0f;
                NSLog(@"mode : %@", mode);
                
                btn.enabled = YES;
                btn.imgvMode.highlighted = YES;
                btn.imgvBtnBg.highlighted = YES;
                btn.imgvCheck.hidden = NO;
                
            } else {//일반모드
                [btn sd_setImageWithURL:[NSURL URLWithString:mode.imageFileName] forState:UIControlStateNormal];
                //                btn.label.textColor = kUITextColor04;
                //                btn.label.alpha = 1.0f;
                btn.enabled = YES;
                btn.imgvMode.highlighted = NO;
                btn.imgvBtnBg.highlighted = NO;
                btn.imgvCheck.hidden = YES;
            }
        }
        
        i++;
    }
    
}

- (void)doChangeHomeMode:(NSString *)modeCode {
    
    if (![JDFacade facade].loginUser.isHomehubOnline || ![JDFacade facade].loginUser.hasHomeHub) {
        [[JDFacade facade] toast:@"홈허브가 온라인 상태로\n연결되어 있을 때 시도해주세요"];
        return;
    }
    
    if(![[JDFacade facade].loginUser.gradeCode isEqualToString:KNEET_MEMBER_MASTER]) {
        return;
    }
    
    ModeModel *mode = [_dashboard.modeList objectKey:@"basicModeCode" eqaulToString:modeCode];
    
    //이미 사용중이면 통신 안함.
    if ([mode.useYn boolValue]) return;
    
    
    //    로직 변경
    //        if (!mode.homegrpSceneId || [mode.homegrpSceneId isEmptyString]) {
    //
    //            if ([JDFacade facade].loginUser.level < 90) {//일반 멤버
    //                [[JDFacade facade] toast:@"아직 선택된 장치가 없습니다.\r장치선택은 마스터만 할 수 있습니다."];
    //            } else {
    //                HomeModeSettingsViewController *vc = (HomeModeSettingsViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"HomeModeSettingsViewController" storyboardName:@"Main"];
    //                vc.mode = mode;
    //
    //                [self presentViewController:vc animated:YES completion:nil];
    //            }
    //            return;
    //        }
    
    //    HomeModeUpdateViewController *vc = (HomeModeUpdateViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"HomeModeUpdateViewController" storyboardName:@"Main"];
    //    vc.mode = mode;
    //    [self presentViewController:vc animated:YES completion:nil];
    
    
    //parameters
    NSDictionary *parameter = @{@"basic_mode_code": modeCode,
                                @"mode_id": mode.modeId};
    
    //    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_POST_DASHBOARD_MODE_CHANGE arguments:nil];
    
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_PUT_DASHBOARD_MODE_CHANGE arguments:nil];
    
    [[RequestHandler handler] sendAsyncPutRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        [self requestDashboard:nil];
        [self setContents];
        //        if ([[JDFacade facade].currentViewController isEqual:self]) {
        //
        //            //check requet done,
        //            _requestTime = [NSDate systemDate];
        //
        //            if (_mode.homegrpSceneId && ![_mode.homegrpSceneId isEmptyString]) {//제어할 장치가 있는 경우,
        //                [self requestPollingHomeModeChanges];
        //            } else {
        //                [self setContentsForComplete];
        //            }
        //        }
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
    
    
}
- (void)requestChangeHomeMode {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
