//
//  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"

@interface MainViewController () <ImageUtilDelegate> {
    ThingsViewController *_tvc;
    RulesViewController *_rvc;
    HomeMemberViewController *_mvc;
    
    ImageUtil *_imageUtil;
    
    NSDate *_readDateTime;
    
    DashboardModel *_dashboard;
}

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

@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 = IPHONE_HEIGHT - kfMainTabBarHeight;
    [_scrollView setContentSize:CGSizeMake(IPHONE_WIDTH * 3, height)];
    _scrollView.pagingEnabled = YES;
    _scrollView.scrollEnabled = NO;
    
    
    CGRect sr = CGRectMake(0, 0, IPHONE_WIDTH, height);
    
    //init child view for childViewController
    _thingsContainerView = [[UIView alloc] initWithFrame:sr];
    _rulesContainerView = [[UIView alloc] initWithFrame:sr];
    _membersContainerView = [[UIView alloc] initWithFrame:sr];
    
    [_scrollView addSubview:_thingsContainerView];
    
    _rulesContainerView.x = IPHONE_WIDTH;
    [_scrollView addSubview:_rulesContainerView];
    
    _membersContainerView.x = IPHONE_WIDTH * 2;
    [_scrollView addSubview:_membersContainerView];
    
    //when first loading this view.
    [self initThingsViewController];
    
    _btnHomeHub.enabled = !(![JDFacade facade].loginUser.homehubDeviceId || [[JDFacade facade].loginUser.homehubDeviceId isEmptyString]);
}

- (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)prepareViewDidLoad {
    [self requestDashboard];
    
    [[JDFacade facade] checkHomeHubStatus];
}

#pragma mark - Main Logic

- (void)updateHomeHubStatusToChildViewController {
    if (_tvc) {
        [_tvc updateHomeHubStatusToDevices];
    }
    
    if (_rvc) {
        [_rvc updateHomeHubStatusToRules];
    }
    
    if (_mvc) {
        [_mvc updateHomeHubStatusToMembers];
    }
}

- (void)requestDashboard {
    //parameters
    NSDictionary *parameter = @{@"read_datetime": [JDFacade facade].loginUser.noticeReadTime ? [JDFacade facade].loginUser.noticeReadTime : ksEmptyString};
    
    NSString *path = [NSString stringWithFormat:API_GET_DASHBOARD];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[DashboardModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DashboardModel *dashboard = (DashboardModel *) responseObject;
        
        if (dashboard) {//API 성공 ,
            _dashboard = dashboard;
            [self setContents];
        }
    } 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.imageFileName;
            [_btnHomegrpImage sd_setImageWithURL:[NSURL URLWithString:response.imageFileName] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
            [[JDFacade facade] toast:@"홈 이미지를 변경했습니다"];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)setContents {
    [_btnHomegrpImage sd_setImageWithURL:[NSURL URLWithString:_dashboard.imageFileName] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
}

#pragma mark - ImageUtil delegate

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

#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];
        
        [_tvc prepareViewDidLoad];
    }];
}

- (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];
    }];
}

- (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];
    }];
}

#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 {
    
    _constraintExpandViewTop.constant = -IPHONE_HEIGHT;
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (IBAction)btnCollapseTouched:(id)sender {
    
    _constraintExpandViewTop.constant = 0;
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        [self.view layoutIfNeeded];
    }];
}

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

- (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.homehubDeviceId || [[JDFacade facade].loginUser.homehubDeviceId isEmptyString]) {
        [[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];
}



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

@end