//
//  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 "DeleteAccountPopupView.h"
#import "ChangeNamePopupView.h"
#import "ConfirmPasswdPopupView.h"
#import "ChangeEmailPopupView.h"
#import "ChangePhotoPopupView.h"
#import "ManagementViewController.h"
#import "HomeModeMovementViewController.h"

#define kiAccountCellHeight 555
#define kiNotiCellHeight 137
#define kiServiceCellHeight 143
#define kiVersionCellHeight 137
#define kiDeleteCellHeight 82
//#define kiPasswdCellHeight 135
#define kiPhotoAlbum 0
#define kiPhotoCamera 1
#define kiPhotoDelete 2

@implementation SettingsAccountTableViewCell

- (void)awakeFromNib {
}

- (void)didMoveToSuperview {
//    [_lblChangeNickname setUnderLine:_lblChangeNickname.text];
//    [_lblChangePassword setUnderLine:_lblChangePassword.text];
//    [_lblChangeEmail setUnderLine:_lblChangeEmail.text];
    
//    [_lblChangePassword setHidden:NO];
    [_lblChangeEmail setHidden:YES];
    [_lblEmailWaiting setHidden:YES];
    
    _btnProfile.layer.frame = CGRectMake(0, 0, _btnProfile.frame.size.width, _btnProfile.frame.size.width);
    _btnProfile.layer.masksToBounds = YES;
    _btnProfile.layer.cornerRadius = _btnProfile.frame.size.width/2;
    
    _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 SettingsDeleteTableViewCell

@end

//@implementation SettingsPasswdTableViewCell
//
//@end

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


#pragma mark - Class Definition

@implementation SettingsViewController
@synthesize dashboardModel;

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

}


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

- (void)initUI {
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    //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 {
    NSDictionary *parameter;
    BOOL imageIsNull = NO;
    
    if (profileImage == nil) { // 사진 삭제
        parameter = @{@"image_file": @""};
        imageIsNull = YES;
    } else {
        parameter = @{@"image_file": profileImage};
        imageIsNull = NO;
    }

    //parameters
//    NSDictionary *parameter = @{@"image_file": profileImage};
    
//    NSString *path = [NSString stringWithFormat:API_POST_MEMBER_UPDATE_IMAGE];
    NSString *path = [[JDFacade facade] getUrlWithCustGroupIDAndMemberID:API_POST_MEMBER_UPDATE_IMAGE];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[LoginModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        LoginModel *response = (LoginModel *) responseObject;
        
        NSLog(@"responseObject : %@",responseObject);

        if (response) {//API 성공
            
            if (!imageIsNull) {
                [_btnProfile sd_setBackgroundImageWithURL:[NSURL URLWithString:response.imageFile] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_member_photo_default"] options:SDWebImageRefreshCached];
                
                [JDFacade facade].loginUser.profileImage = response.imageFile;
                
                [[JDFacade facade] toast:@"프로필 이미지를 변경했습니다"];
            } else {
                    NSString *msg = @"사진이 삭제 되었습니다.";
                    [[JDFacade facade] alertTitle:@"알림" message: msg completionHander:nil];

                [_btnProfile sd_setBackgroundImageWithURL:[NSURL URLWithString:response.imageFile] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_member_photo_default"] options:SDWebImageRefreshCached];
                
                [JDFacade facade].loginUser.profileImage = response.imageFile;
            }
        }
    } 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;
        height = kiAccountCellHeight;
    } else if (indexPath.section == 1) {//notification view
//        height = [JDFacade facade].loginUser.isHomehubOnline ? 317-56 : 317;
        height = kiNotiCellHeight;
    } else if (indexPath.section == 2) {
        height = kiServiceCellHeight;
    } else if (indexPath.section == 3) {
        height = kiVersionCellHeight;
    } else if (indexPath.section == 4) {
        height = kiDeleteCellHeight;
    }
//    else if (indexPath.section == 5) {
//        height = kiPasswdCellHeight;
//    }
    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 isEqualToString:@""] ? @"사용자 이름을 등록해주세요.":[JDFacade facade].loginUser.nickname;
        
        tcell.lblEmail.text = [JDFacade facade].loginUser.memberId;
        tcell.lblQuiz.text = [JDFacade facade].loginUser.quiz;
        
        if (!_btnProfile) {
            _btnProfile = tcell.btnProfile;
        }
        
        [_btnProfile sd_setBackgroundImageWithURL:[NSURL URLWithString:[JDFacade facade].loginUser.profileImage] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_member_photo_default"] options:SDWebImageRefreshCached];
        
        tcell.lblPhoneNum.text = [CommonUtil formattedPhoneNumber:[JDFacade facade].loginUser.phone];
        
        //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];
            }];
        }
        
        //set Phone Number change action
        if (![tcell.btnChangeNum actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {//set button target
            [tcell.btnChangeNum addTarget:self action:@selector(btnChangeNumTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        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 ([JDFacade facade].loginUser.level < 90) {
            tcell.viewThingsSet.hidden = YES;
        } else {
            tcell.viewThingsSet.hidden = NO;
        }
        
        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.btnThingsSet actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnThingsSet addTarget:self action:@selector(btnThingsSetTouched:) 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 applicationShortVersion]];
        
        if (![tcell.btnLicense actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnLicense addTarget:self action:@selector(btnLicenseTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    } else if (indexPath.section == 4) {//Delete cell
        SettingsDeleteTableViewCell *tcell = [_tableView dequeueReusableCellWithIdentifier:@"DeleteCellIdentifier"];

        if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    }
//    else if (indexPath.section == 5) {//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];
//        }
//    }];
   UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SettingsNameSetViewController" storyboardName:@"Settings"];
//    vc.providesPresentationContextTransitionStyle = YES;
//    vc.definesPresentationContext = YES;
//
//    [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
//
//    [self presentViewController:vc animated:YES completion:nil];

    [self.navigationController pushViewController:vc animated:YES];
}

- (void)lblChangePasswordTouched {
//    ConfirmPasswdPopupView *popup = [[ConfirmPasswdPopupView alloc] initFromNib];
//    [popup show];
    
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SettingsPasswdInputViewController" storyboardName:@"Settings"];
    
    [self.navigationController pushViewController:vc animated:YES];
}

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


- (void)btnProfileTouched:(id)sender {
    
    if (!_imageUtil) {
        _imageUtil = [[ImageUtil alloc] init];
        _imageUtil.delegate = self;
    }
    
//    [_imageUtil prepareImagePicker:self];
    ChangePhotoPopupView *popup = [[ChangePhotoPopupView alloc]initFromNib];
    [popup show];
    
    popup.delegate = self;
}

-(void)changeSelectPhotoType:(NSInteger)index{
    [_imageUtil setPresentViewController:self];

    if (index == kiPhotoAlbum) {
        [_imageUtil showImagePickerController:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    } else if (index == kiPhotoCamera){
        [_imageUtil showImagePickerController:UIImagePickerControllerSourceTypeCamera];
    } else if (index == kiPhotoDelete){
//        UIImage *image = [[UIImage alloc]init];
        [self requestUpdateProfileImage:[UIImage imageNamed:@""]];
    }
}

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

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

- (void)btnChangeNumTouched:(id)sender {
    
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SettingsNumChangeViewController" storyboardName:@"Settings"];
    
    [self.navigationController pushViewController:vc animated:YES];
}

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

// 홈모드별 동작할 장치 설정 이동
- (void)btnThingsSetTouched:(id)sender{
    HomeModeMovementViewController *vc =[CommonUtil instantiateViewControllerWithIdentifier:@"HomeModeMovementViewController" storyboardName:@"Main"];
    
    vc.modeArray = dashboardModel.modeList;

    [self.navigationController pushViewController:vc animated:YES];
}

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

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

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

- (void)btnLicenseTouched:(id)sender { //오픈소스 라이선스
    NSString *URLString = [NSString stringWithFormat:@"%@%@", kWebLinkServer, URL_PATH_POLICY];
    [[JDFacade facade] loadURLExternalBrowser:URLString];
    
}

- (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
