//
//  MainViewController.m
//  kneet2
//
//  StoryBoard - page 8.
//
//  Created by Jason Lee on 10/2/15.
//  Copyright © 2015 ntels. All rights reserved.
//

#import "JDObject.h"

#import "RequestHandler.h"

#import "CustomButton.h"
#import "UIButton+WebCache.h"
#import "ImageUtil.h"

#import "ThingsViewController.h"
#import "RulesViewController.h"
#import "HomeMemberViewController.h"

#import "MainViewController.h"
#import "HomeModeUpdateViewController.h"
#import "HomeModeSettingsViewController.h"
#import "ManagementViewController.h"

#import "CustomLabelButton.h"
#import "CustomImageView.h"
#import "PwdPopupView.h"



@interface MainViewController () <ImageUtilDelegate> {
    
    RulesViewController *_rvc;
    HomeMemberViewController *_mvc;
    ManagementViewController *_manageVc;
    
    ImageUtil *_imageUtil;
    
    NSDate *_readDateTime;
    
    DashboardModel *_dashboard;
    BOOL _isNotFirstLoading;
}

@property (strong, nonatomic) JDViewController *currentChildViewController;
@property (strong, nonatomic) UIView *thingsContainerView;
@property (strong, nonatomic) UIView *rulesContainerView;
@property (strong, nonatomic) UIView *membersContainerView;
@property (strong, nonatomic) UIView *manageContainerVIew;

@end


#pragma mark - Class Definition

@implementation MainViewController


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

- (void)initUI {
    //1. init tabBar
    //1-1. scroll top bottom
    
    
    //2. init scrollView
    //    CGFloat height = ViewHeight(_scrollView); //IPHONE_HEIGHT - kfMainTabBarHeight;
    [_scrollView setContentSize:CGSizeMake(IPHONE_WIDTH * 4, IPHONE_HEIGHT)];
    _scrollView.pagingEnabled = YES;
    _scrollView.scrollEnabled = NO;
    
    
    CGRect sr = CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT);
    
    //init child view for childViewController
    _thingsContainerView = [[UIView alloc] initWithFrame:sr];
    _rulesContainerView = [[UIView alloc] initWithFrame:sr];
    _membersContainerView = [[UIView alloc] initWithFrame:sr];
    _manageContainerVIew = [[UIView alloc] initWithFrame:sr];
    
    [_scrollView addSubview:_thingsContainerView];
    
    _rulesContainerView.x = IPHONE_WIDTH;
    [_scrollView addSubview:_rulesContainerView];
    
    _membersContainerView.x = IPHONE_WIDTH * 2;
    [_scrollView addSubview:_membersContainerView];
    
    _manageContainerVIew.x = IPHONE_WIDTH * 3;
    [_scrollView addSubview:_manageContainerVIew];
    
    _constraintExpandViewTop.constant = -IPHONE_HEIGHT;
    _constraintExpandViewHeight.constant = IPHONE_HEIGHT;
    
    [self.view layoutIfNeeded];
}


- (void)initThingsViewController {
    
    if (!_tvc) {
        _tvc = (ThingsViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsViewController" storyboardName:@"Things"];
    }
    
    [self addChildViewController:_tvc];
    [_tvc didMoveToParentViewController:self];
    
    if ([self isViewLoaded]) {
        [_tvc beginAppearanceTransition:YES animated:NO];
        [_thingsContainerView addSubview:_tvc.view];
        [_tvc endAppearanceTransition];
    }
}


- (void)initRulesViewController {
    
    if (!_rvc) {
        _rvc = (RulesViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesViewController" storyboardName:@"Rules"];
    }
    
    [self addChildViewController:_rvc];
    [_rvc didMoveToParentViewController:self];
    
    if ([self isViewLoaded]) {
        [_rvc beginAppearanceTransition:YES animated:NO];
        [_rulesContainerView addSubview:_rvc.view];
        [_rvc endAppearanceTransition];
    }
}

- (void)initMembersViewController {
    if (!_mvc) {
        _mvc = (HomeMemberViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"HomeMemberViewController" storyboardName:@"HomeMember"];
    }
    
    [self addChildViewController:_mvc];
    [_mvc didMoveToParentViewController:self];
    
    if ([self isViewLoaded]) {
        [_mvc beginAppearanceTransition:YES animated:NO];
        [_membersContainerView addSubview:_mvc.view];
        [_mvc endAppearanceTransition];
    }
}

- (void)initManagementViewController {
    if (!_manageVc) {
        _manageVc = (ManagementViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ManagementViewController" storyboardName:@"Main"];
    }
    
    [self addChildViewController:_manageVc];
    [_manageVc didMoveToParentViewController:self];
    
    if ([self isViewLoaded]) {
        [_manageVc beginAppearanceTransition:YES animated:NO];
        [_manageContainerVIew addSubview:_manageVc.view];
        [_manageVc endAppearanceTransition];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [self requestDashboard:nil];
}

- (void)prepareViewDidLoad {
    //    [self requestDashboard:nil];
    
    //    [[JDFacade facade] requestPollingHomeHubStatusInBackground];
    // TODO: 웹소켓 연결해서 정보 받아오는 형식으로 전환할것
}

- (void)setCurrentChildViewController:(JDViewController *)currentChildViewController {
    _currentChildViewController = currentChildViewController;
    
    if (![_currentChildViewController isEqual:_tvc]) {
        [_tvc releaseDevicesTimer];
    }
}

#pragma mark - Main Logic

- (void)updateHomeHubStatusToChildViewController {
    
    //    [self setContents];
    //[self checkTempPassword];
    
    if (_tvc) {
        [_tvc updateHomeHubStatusToDevices];
    }
    
    if (_rvc) {
        [_rvc updateHomeHubStatusToRules];
    }
    
    if (_mvc) {
        [_mvc updateHomeHubStatusToMembers];
    }
    if (_manageVc) {
        [_manageVc updateHomeHubStatusToManage];
    }
}

- (void)updateCurrentViewController {
    if ([_currentChildViewController isEqual:_tvc]) {
        [_tvc prepareViewDidLoadRefreshPopup];
    } else if ([_currentChildViewController isEqual:_rvc]) {
        [_rvc prepareViewDidLoad];
    } else if ([_currentChildViewController isEqual:_mvc]) {
        [_mvc prepareViewDidLoad];
    } else if([_currentChildViewController isEqual:_manageVc]) {
        [_manageVc prepareViewDidLoad];
    }
}

- (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];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[DashboardModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DashboardModel *dashboard = (DashboardModel *) responseObject;
        NSLog(@"DashBoard Info : %@", responseObject);
        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];
            //[self checkTempPassword];
        }
        
        if (completion) {
            completion();
        }
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestUpdateHomeGroupImage:(UIImage *)profileImage {
    
    //parameters
    NSDictionary *parameter = @{@"image_file": profileImage};
    
    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_UPDATE_IMAGE];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[LoginModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        LoginModel *response = (LoginModel *)responseObject;
        
        if (response) {//API 성공 ,
            
            _dashboard.imageFileName = response.profileImage;
            [_btnHomegrpImage sd_setImageWithURL:[NSURL URLWithString:response.profileImage] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
            [[JDFacade facade] toast:@"홈 이미지를 변경했습니다"];
        }
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

////extendView 컨텐츠 설정
//- (void)setContents {
//
//    _lblNoticeCount.text = _dashboard.noticeCount;
//    _lblPushCount.text = _dashboard.pushCount;
//    _imgvHomehubOff.hidden = [JDFacade facade].loginUser.isHomehubOnline;
//
//
//    _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;
//
//        } else {
//
//            if ([mode.useYn boolValue]) {//활성모드
//                [btn sd_setImageWithURL:[NSURL URLWithString:mode.imageFileActiveName] forState:UIControlStateNormal];
//                btn.label.textColor = kUITextColor01;
//                btn.label.alpha = 1.0f;
//                btn.enabled = YES;
//
//            } else {//일반모드
//                [btn sd_setImageWithURL:[NSURL URLWithString:mode.imageFileName] forState:UIControlStateNormal];
//                btn.label.textColor = kUITextColor04;
//                btn.label.alpha = 1.0f;
//                btn.enabled = YES;
//            }
//        }
//
//        i++;
//    }
//
//    [self checkTempPassword];
//}

// TODO : 임시 비밀번호 변경관련 작업 할것.
- (void)checkTempPassword {
    
    if ([JDFacade facade].loginUser.tempPasswordYn && [[JDFacade facade].loginUser.tempPasswordYn boolValue]) {
        [[JDFacade facade] confirm:@"임시 비밀번호를 변경해주세요" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {//OK
                PwdPopupView *popup = [[PwdPopupView alloc] initFromNib];
                [popup show];
            }
        }];
    }
}

- (void)updateRulesListRecently {
    [_rvc prepareViewDidLoad];
}

#pragma mark - ImageUtil delegate

- (void)didFinishPickingImage:(UIImage *)image {
    [self requestUpdateHomeGroupImage:image];
}

#pragma mark - SocketServiceHandler delegate
-(void)socketConnectComplete
{
    //    NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
    //
    //    data[@"message_type"] = @"auth";
    //    data[@"member_id"] = @"100";
    //    data[@"password"] = @"1234";
    //    data[@"os_type"] = @"MA";
    //    data[@"cust_id"] = @"1002";
    //    data[@"ctrt_grp_id"] = @"1002";
    //
    //
    //    [[SocketServiceHandler sharedManager] sendData:data];
}

#pragma mark - UI Control
- (void)loadThingsViewController {
    [[JDFacade facade] showLoadingWhileExecutingBlock:^{
        if (!_tvc) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self initThingsViewController];
            });
        }
    } completionHandler:^{
        CGPoint cpoint = CGPointMake(0, 0);
        [_scrollView setContentOffset:cpoint animated:NO];
        
        [_btnThings setHighlighted:YES];
        [_btnRules setHighlighted:NO];
        [_btnMembers setHighlighted:NO];
        [_btnExtend setHighlighted:NO];
        
        [_tvc prepareViewDidLoadRefreshPopup];
        
        self.currentChildViewController = _tvc;
    }];
}

- (void)loadRulesViewController {
    [[JDFacade facade] showLoadingWhileExecutingBlock:^{
        if (!_rvc) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self initRulesViewController];
            });
        }
    } completionHandler:^{
        CGPoint cpoint = CGPointMake(IPHONE_WIDTH, 0);
        [_scrollView setContentOffset:cpoint animated:NO];
        
        [_btnThings setHighlighted:NO];
        [_btnRules setHighlighted:YES];
        [_btnMembers setHighlighted:NO];
        [_btnExtend setHighlighted:NO];
        
        [_rvc prepareViewDidLoad];
        
        self.currentChildViewController = _rvc;
    }];
}

- (void)loadMembersViewController {
    [[JDFacade facade] showLoadingWhileExecutingBlock:^{
        if (!_mvc) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self initMembersViewController];
            });
        }
    } completionHandler:^{
        CGPoint cpoint = CGPointMake(IPHONE_WIDTH * 2, 0);
        [_scrollView setContentOffset:cpoint animated:NO];
        
        [_btnThings setHighlighted:NO];
        [_btnRules setHighlighted:NO];
        [_btnMembers setHighlighted:YES];
        [_btnExtend setHighlighted:NO];
        
        [_mvc prepareViewDidLoad];
        
        self.currentChildViewController = _mvc;
    }];
}

- (void)loadManagementViewController {
    [[JDFacade facade] showLoadingWhileExecutingBlock:^{
        if (!_manageVc) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self initManagementViewController];
            });
        }
    } completionHandler:^{
        CGPoint cpoint = CGPointMake(IPHONE_WIDTH * 3, 0);
        [_scrollView setContentOffset:cpoint animated:NO];
        
        [_btnThings setHighlighted:NO];
        [_btnRules setHighlighted:NO];
        [_btnMembers setHighlighted:NO];
        [_btnExtend setHighlighted:YES];
        
        [_manageVc prepareViewDidLoad];
        
        self.currentChildViewController = _manageVc;
    }];
}

#pragma mark - UI Events
- (IBAction)btnThingsTouched:(id)sender {
    [self loadThingsViewController];
}

- (IBAction)btnRuleTouched:(id)sender {
    [self loadRulesViewController];
}

- (IBAction)btnMemberTouched:(id)sender {
    [self loadMembersViewController];
}

- (IBAction)btnExtendTouched:(id)sender {
    [self loadManagementViewController];
    //    _constraintExpandViewTop.constant = -IPHONE_HEIGHT;
    //
    //    [UIView animateWithDuration:kfAnimationDur animations:^{
    //        [self.view layoutIfNeeded];
    //    } completion:^(BOOL finished) {
    //        [self requestDashboard:nil];
    //    }];
}

//- (IBAction)btnCollapseTouched:(id)sender {
//
//    _constraintExpandViewTop.constant = 0;
//
//    [UIView animateWithDuration:kfAnimationDur animations:^{
//        [self.view layoutIfNeeded];
//    } completion:^(BOOL finished) {
//
//        if ([_currentChildViewController isEqual:_tvc]) {
//            [_tvc prepareViewDidLoad];
//        }
//    }];
//}

//- (IBAction)btnProfileTouched:(id)sender {
//    if (!_imageUtil) {
//        _imageUtil = [[ImageUtil alloc] init];
//        _imageUtil.delegate = self;
//    }
//
//    [_imageUtil prepareImagePicker:self];
//}

//- (IBAction)btnNoticeTouched:(id)sender {
//    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"NoticeViewController" storyboardName:@"Main"];
//    [self presentViewController:vc animated:YES completion:nil];
//}
//
//- (void)btnMessageBoxTouched:(id)sender {
//    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MessageBoxViewController" storyboardName:@"Main"];
//    [self presentViewController:vc animated:YES completion:nil];
//}
//
//- (void)btnHomeHubTouched:(id)sender {
//
//    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubViewController" storyboardName:@"Main"];
//    [self presentViewController:vc animated:YES completion:nil];
//}
//
//- (IBAction)btnSettingsTouched:(id)sender {
//
//    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SettingsViewController" storyboardName:@"Settings"];
//    [self presentViewController:vc animated:YES completion:nil];
//}
//
//- (IBAction)btnModeHomeTouched:(id)sender {
//    [self doChangeHomeMode:HOME_MODE_HOME];
//}
//
//- (IBAction)btnModeAwayTouched:(id)sender {
//    [self doChangeHomeMode:HOME_MODE_AWAY];
//}
//
//- (IBAction)btnModeMorningTouched:(id)sender {
//    [self doChangeHomeMode:HOME_MODE_MORNING];
//}
//
//- (IBAction)btnModeNightTouched:(id)sender {
//    [self doChangeHomeMode:HOME_MODE_NIGHT];
//}
//
//- (void)doChangeHomeMode:(NSString *)modeCode {
//
//    if (![JDFacade facade].loginUser.isHomehubOnline || ![JDFacade facade].loginUser.hasHomeHub) {
//        [[JDFacade facade] toast:@"홈허브가 온라인 상태로\n연결되어 있을 때 시도해주세요"];
//        return;
//    }
//
//    ModeModel *mode = [_dashboard.modeList objectKey:@"basicModeCode" eqaulToString:modeCode];
////로직 변경
////    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];
//}
//
//- (IBAction)btnDashboardRefresh:(id)sender {
//    [self requestDashboard:nil];
//}

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

@end
