//
//  SettingsViewController.m
//  kneet2
//
//  Created by Jason Lee on 10/8/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

#import "RequestHandler.h"

#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomCheckBox.h"
#import "UIButton+WebCache.h"
#import "CustomTableView.h"

#import "WebBrowseViewController.h"

#import "PwdPopupView.h"
#import "ImageUtil.h"
#import "SettingsViewController.h"
#import "AdminAuthPopupView.h"
#import "ChangeNamePopupView.h"
#import "ConfirmPasswdPopupView.h"
#import "ChangeEmailPopupView.h"


@implementation SettingsAccountTableViewCell

- (void)awakeFromNib {
}

- (void)didMoveToSuperview {
    [_lblChangeNickname setUnderLine:_lblChangeNickname.text];
    [_lblChangePassword setUnderLine:_lblChangePassword.text];
    [_lblChangeEmail setUnderLine:_lblChangeEmail.text];
    
    _contraintEmailChangeBottom.constant = ![JDFacade facade].tmpEmailId || [[JDFacade facade].tmpEmailId isEmptyString] ? 18 : 45;
    _lblEmailWaiting.hidden = ![JDFacade facade].tmpEmailId || [[JDFacade facade].tmpEmailId isEmptyString];
    
    [self layoutIfNeeded];
}

@end

@implementation SettingsNotificationTableViewCell


@end

@implementation SettingsServiceTableViewCell

- (void)didMoveToSuperview {
}

@end

@implementation SettingsVersionTableViewCell

@end

@implementation SettingsPasswdTableViewCell

@end

@interface SettingsViewController () <UITableViewDataSource, UITableViewDelegate, ImageUtilDelegate> {
    CustomCheckBox *_chkAutoLogin, *_chkHomeModeChange, *_chkHomeEmptyChange;
    CustomButton *_btnProfile;
    BOOL _isNotFirstLoading;
    
    ImageUtil *_imageUtil;
}
@end


#pragma mark - Class Definition

@implementation SettingsViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

- (void)initUI {

    //set tableview option
    [self initTableViewAsDefaultStyle:_tableView];
}

- (void)prepareViewDidLoad {

}

#pragma mark - Main Logic

- (void)requestUpdatePushSetting:(NSDictionary *)parameter {
    //parameters
    NSString *path = [NSString stringWithFormat:API_POST_PUSH_SETTINGS];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        NSString *msg = nil;
        if ([parameter hasKey:@"push_type_mode_chg_yn"]) {
            
            BOOL isNotifyHomeModeChange = [[parameter valueForKey:@"push_type_mode_chg_yn"] boolValue];
            if ([[JDFacade facade].loginUser.pushTypeModeChgYn boolValue] != isNotifyHomeModeChange) {
                msg = isNotifyHomeModeChange ? @"지금부터 홈모드가 바뀔 때\n푸시 알림을 받습니다" : @"홈모드 변경 알림을 해제합니다";
                [JDFacade facade].loginUser.pushTypeModeChgYn = [parameter valueForKey:@"push_type_mode_chg_yn"];
            }
            
        } else if ([parameter hasKey:@"push_type_prsnc_chg_yn"]) {//와이파이,
            
            BOOL isNotifyExecutingRules = [[parameter valueForKey:@"push_type_prsnc_chg_yn"] boolValue];
            if ([[JDFacade facade].loginUser.pushTypePrsncChgYn boolValue] != isNotifyExecutingRules) {
                msg = isNotifyExecutingRules ? @"지금부터 집이 빌 때\n푸시 알림을 받습니다" : @"빈 집 알림을 해제합니다";
                [JDFacade facade].loginUser.pushTypePrsncChgYn = [parameter valueForKey:@"push_type_prsnc_chg_yn"];
            }
        }
        
        [[JDFacade facade] toast:msg];

    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestUpdateProfileImage:(UIImage *)profileImage {
    
    //parameters
    NSDictionary *parameter = @{@"image_file": profileImage};
    
    NSString *path = [NSString stringWithFormat:API_POST_MEMBER_UPDATE_IMAGE];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[LoginModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        LoginModel *response = (LoginModel *) responseObject;
        
        if (response) {//API 성공 ,
            [_btnProfile sd_setBackgroundImageWithURL:[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];
    }];
}

#pragma mark - UITableView DataSource & Delegate

#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0.0f;
    
    if (indexPath.section == 0) {
        height = ![JDFacade facade].tmpEmailId || [[JDFacade facade].tmpEmailId isEmptyString] ? 331-27 : 331;
        
    } else if (indexPath.section == 1) {//notification view
        height = [JDFacade facade].loginUser.isHomehubOnline ? 317-56 : 317;
    } else if (indexPath.section == 2) {
        height = 181;
    } else if (indexPath.section == 3) {
        height = 191;
    } else if (indexPath.section == 4) {
        height = 135;
    }
    
    return height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;//[super tableView:tableView cellForRowAtIndexPath:indexPath];
    
    if (indexPath.section == 0) {//account cell
        
        SettingsAccountTableViewCell *tcell = [_tableView dequeueReusableCellWithIdentifier:@"AccountCellIdentifier"];
        
        tcell.lblNickname.text = [JDFacade facade].loginUser.nickname;
        tcell.lblEmail.text = [JDFacade facade].loginUser.emailId;
        
        if (!_btnProfile) {
            _btnProfile = tcell.btnProfile;
        }
        
        [_btnProfile sd_setBackgroundImageWithURL:[NSURL URLWithString:[JDFacade facade].loginUser.imageFileName] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
        
        //set checkbox
        if (!_chkAutoLogin) {
            _chkAutoLogin = tcell.chkAutoLogin;
            _chkAutoLogin.checked = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_AUTO_LOGIN] boolValue];
            
        }
        
        //set checkbox action
        if (![_chkAutoLogin actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [_chkAutoLogin addTarget:self action:@selector(chkAutoLoginTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        //set label action
        if (!tcell.lblChangeNickname.touchHandler) {
            [tcell.lblChangeNickname addTouchEventHandler:^(id label) {
                [self lblChangeNicknameTouched];
            }];
        }
        
        //set label action
        if (!tcell.lblChangePassword.touchHandler) {
            [tcell.lblChangePassword addTouchEventHandler:^(id label) {
                [self lblChangePasswordTouched];
            }];
        }
        
        //set email change action
        if (!tcell.lblChangeEmail.touchHandler) {
            [tcell.lblChangeEmail addTouchEventHandler:^(id label) {
                [self lblChangeEmailTouched];
            }];
        }
        
        if (![tcell.btnLogout actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {//set button target
            [tcell.btnLogout addTarget:self action:@selector(btnLogoutTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (![tcell.btnProfile actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {//set button target
            [tcell.btnProfile addTarget:self action:@selector(btnProfileTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (![tcell.btnProfileSetting actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnProfileSetting addTarget:self action:@selector(btnProfileTouched:) forControlEvents:UIControlEventTouchUpInside];
        }

        cell = tcell;
    } else if (indexPath.section == 1) {//notification cell
         SettingsNotificationTableViewCell *tcell = [_tableView dequeueReusableCellWithIdentifier:@"NotificationCellIdentifier"];
        
        if (!_chkHomeModeChange) {
            _chkHomeModeChange = tcell.chkHomeModeChange;
        }
        
        if (!_chkHomeEmptyChange) {
            _chkHomeEmptyChange = tcell.chkHomeEmptyChange;
        }
        
        if (!_isNotFirstLoading) {
            _isNotFirstLoading = YES;
            
            _chkHomeModeChange.checked = [[JDFacade facade].loginUser.pushTypeModeChgYn boolValue];
            _chkHomeEmptyChange.checked = [[JDFacade facade].loginUser.pushTypePrsncChgYn boolValue];
        }
        
        if (![tcell.chkHomeModeChange actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.chkHomeModeChange addTarget:self action:@selector(chkHomeModeChangeTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (![tcell.chkHomeEmptyChange actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.chkHomeEmptyChange addTarget:self action:@selector(chkHomeEmptyChangeTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        tcell.homehubInfoView.hidden = [JDFacade facade].loginUser.isHomehubOnline;
        if (tcell.homehubInfoView.hidden) {
            tcell.constraintHomehubInfoViewHeight.constant = 0;
        } else {
            _chkHomeModeChange.enabled = NO;
            _chkHomeEmptyChange.enabled = NO;
        }
        
        cell = tcell;
    } else if (indexPath.section == 2) {//service info cell
        SettingsServiceTableViewCell *tcell = [_tableView dequeueReusableCellWithIdentifier:@"ServiceCellIdentifier"];
        
        if (![tcell.btnService actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnService addTarget:self action:@selector(btnServiceTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (![tcell.btnPolicy actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnPolicy addTarget:self action:@selector(btnPolicyTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    } else if (indexPath.section == 3) {//version info cell
        SettingsVersionTableViewCell *tcell = [_tableView dequeueReusableCellWithIdentifier:@"VersionCellIdentifier"];
        tcell.lblVersion.text = [NSString stringWithFormat:@"버전 : %@", [CommonUtil applicationVersion]];
        
        cell = tcell;
    } else if (indexPath.section == 4) {//Passwd info cell
        SettingsPasswdTableViewCell *tcell = [_tableView dequeueReusableCellWithIdentifier:@"PasswdCellIdentifier"];

        if (![tcell.btnPassword actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnPassword addTarget:self action:@selector(btnPasswordTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
}

#pragma mark - ImageUtil Delegate
- (void)didFinishPickingImage:(UIImage *)image {
    [self requestUpdateProfileImage:image];
}

#pragma mark - UI Events
- (void)lblChangeNicknameTouched {
    ChangeNamePopupView *popup = [[ChangeNamePopupView alloc] initFromNib];
    [popup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//이름 변경 시,
            [_tableView reloadData];
        }
    }];
}

- (void)lblChangePasswordTouched {
    ConfirmPasswdPopupView *popup = [[ConfirmPasswdPopupView alloc] initFromNib];
    [popup show];
}

- (void)lblChangeEmailTouched {
    ChangeEmailPopupView *popup = [[ChangeEmailPopupView alloc] initFromNib];
    [popup show];
}


- (IBAction)btnProfileTouched:(id)sender {
    
    if (!_imageUtil) {
        _imageUtil = [[ImageUtil alloc] init];
        _imageUtil.delegate = self;
    }
    
    [_imageUtil prepareImagePicker:self];
}
 
- (IBAction)chkAutoLoginTouched:(id)sender {
    
    [[JDFacade facade] storeObjectToUserDefaults:@(_chkAutoLogin.checked) forKey:USDEF_APP_AUTO_LOGIN];
    
    if (_chkAutoLogin.checked) {//자동로그인 설정 시, 인증 토큰 저장
        [[JDFacade facade] storeObjectToKeychain:[JDFacade facade].loginUser.authToken forKey:USDEF_SESSION_AUTOTOKEN];
    } else {;
        [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN];
    }
}

- (IBAction)btnLogoutTouched:(id)sender {
    [[JDFacade facade] logout];
}


//NoticationcationCell's action

- (void)chkHomeModeChangeTouched:(id)sender {
    
    NSDictionary *parameter = @{@"push_type_mode_chg_yn" : _chkHomeModeChange.checked ? ksYES : ksNO};
    [self requestUpdatePushSetting:parameter];
}

- (void)chkHomeEmptyChangeTouched:(id)sender {

    NSDictionary *parameter = @{@"push_type_prsnc_chg_yn" : _chkHomeEmptyChange.checked ? ksYES : ksNO};
    [self requestUpdatePushSetting:parameter];
}

//service info cell's action

- (void)btnServiceTouched:(id)sender {
    
    
    NSString *URLString = [NSString stringWithFormat:@"%@%@", kAPIServer, URL_PATH_TERMS];
    [[JDFacade facade] loadURLExternalBrowser:URLString];
}

- (void)btnPolicyTouched:(id)sender {
    
    NSString *URLString = [NSString stringWithFormat:@"%@%@", kAPIServer, URL_PATH_POLICY];
    [[JDFacade facade] loadURLExternalBrowser:URLString];
}

//service passwd cell's action
- (void)btnPasswordTouched:(id)sender {//셋탑 설정
    AdminAuthPopupView *popup = [[AdminAuthPopupView alloc] initFromNib];
    [popup show];
}

- (IBAction)btnCloseTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

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

@end
