//
//  AccountViewController.m
//  kneet
//
//  Created by Jason Lee on 5/13/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "CustomLabel.h"
#import "CustomButton.h"

#import "DeleteAccountPopupView.h"
#import "PwdPopupView.h"
#import "ConfirmPwdViewController.h"

#import "AccountViewController.h"
#import "UIButton+WebCache.h"
#import "ChangeIconViewController.h"
#import "RequestHandler.h"

@interface AccountViewController () {
    UIView *_containerView;
    ChangeIconViewController *_ivc;
    CGFloat _containerBottom;
    MASConstraint *_constraintContainerBottom;
}
@end


#pragma mark - Class Definition

@implementation AccountViewController


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

    [self initUI];
}

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

    self.title = NSLocalizedString(@"계정 정보", @"계정 정보");
    [self prepareViewDidLoad];
}

- (void)initUI {

    //set tableview option
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];

    [_lblPwdChange setUnderLine:_lblPwdChange.text];
    [_lblAccountDelete setUnderLine:_lblAccountDelete.text];

    [_lblPwdChange addTouchEventHandler:^(id label) {
        [self lblPwdChangeTouched];
    }];
    
    [_lblAccountDelete addTouchEventHandler:^(id label) {
        [self lblAccountDeleteTouched];
    }];

    [_btnProfile sd_setImageWithURL:[NSURL URLWithString:[JDFacade facade].loginUser.imageFileName] forState:UIControlStateNormal];
    
    _lblNameTitle.text = NSLocalizedString(@"이름", @"이름");
    _lblEmailTitle.text = NSLocalizedString(@"이메일", @"이메일");
    _lblPwdTitle.text = NSLocalizedString(@"비밀번호", @"비밀번호");
    _lblAccountDeleteTitle.text = NSLocalizedString(@"계정삭제", @"계정삭제");
}

- (void)prepareViewDidLoad {
    [_btnName setTitle:[JDFacade facade].loginUser.nickname forState:UIControlStateNormal];
    [_btnEmail setTitle:[JDFacade facade].tmpEmailId forState:UIControlStateNormal];

    _lblNewEmailInfo.hidden = !([JDFacade facade].loginUser.newEmailId && ![[JDFacade facade].loginUser.newEmailId isEmptyString]);
    if (!_lblNewEmailInfo.hidden) {//이메일 변경 요청 중
        _lblNewEmailInfo.text = [NSString stringWithFormat:NSLocalizedString(@"%@ 인증 대기중", @"%@ 인증 대기중"), [JDFacade facade].loginUser.newEmailId];
    }
}

#pragma mark - Main Logic
- (void)requestChangeMemberIcon {
    //parameters
    NSDictionary *parameter = @{@"image_file_name": _ivc && _ivc.selectedIcon ? _ivc.selectedIcon.imageFilePath : ksEmptyString};
    
    NSString *path = [NSString stringWithFormat:API_POST_MEMBER_UPDATE, [JDFacade facade].loginUser.memberId, @"profile"];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        [JDFacade facade].loginUser.imageFileName = _ivc.selectedIcon.imageFileName;
        [_btnProfile sd_setImageWithURL:[NSURL URLWithString:[JDFacade facade].loginUser.imageFileName] forState:UIControlStateNormal];
        
        [[JDFacade facade] toast:NSLocalizedString(@"변경되었습니다", @"변경되었습니다")];
        [self closeChildViewController:_ivc completionHandler:nil];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


#pragma mark - UI Events
- (IBAction)btnNameTouched:(id)sender {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ChangeNameViewController" storyboardName:@"Settings"];
    [self.navigationController pushViewController:vc animated:YES];
}

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

- (void)lblPwdChangeTouched {
    ConfirmPwdViewController *vc = (ConfirmPwdViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ConfirmPwdViewController" storyboardName:@"Settings"];
    vc.popupName = NSStringFromClass([PwdPopupView class]);
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)lblAccountDeleteTouched {
    ConfirmPwdViewController *vc = (ConfirmPwdViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ConfirmPwdViewController" storyboardName:@"Settings"];
    vc.popupName = NSStringFromClass([DeleteAccountPopupView class]);
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)btnProfileTouched:(id)sender {
    [self modifyMemberIcon];	
}


- (void)modifyMemberIcon {
    
    if ([_ivc.view superview]) {
        return;
    }
    
    self.tableView.scrollEnabled = NO;
    
    if (!_ivc) {
        _ivc = (ChangeIconViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ChangeIconViewController" storyboardName:@"Settings"];
        
        [self addChildViewController:_ivc];
        [_ivc didMoveToParentViewController:self];
    }
    
    if (!_containerView) {
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, IPHONE_HEIGHT+STATUS_BAR_HEIGHT, IPHONE_WIDTH, 336)];
        _containerView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_containerView];
    }
    
    [_containerView addSubview:_ivc.view];
    
    if (![_ivc.btnSave actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
        __weak typeof(self) weakSelf = self;
        [_ivc.btnSave addTarget:weakSelf action:@selector(btnSaveTouched:) forControlEvents:UIControlEventTouchUpInside];
        [_ivc.btnCancel addTarget:weakSelf action:@selector(btnCancelTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        CGRect cr = _containerView.frame;
        cr.origin.y = IPHONE_HEIGHT - 336 - 60;
        _containerView.frame = cr;
    }];
}

- (void)closeChildViewController:(UIViewController *)vc completionHandler:(JDFacadeCompletionCallBackHandler)completionHander {
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        CGRect cr = _containerView.frame;
        cr.origin.y = IPHONE_HEIGHT + STATUS_BAR_HEIGHT;
        _containerView.frame = cr;
        
    } completion:^(BOOL finished) {
        self.tableView.scrollEnabled = YES;
        [vc.view removeFromSuperview];
        
        if (completionHander) {
            completionHander();
        }
    }];
}

- (void)btnSaveTouched:(id)sender {
    //기존이랑 같으면, 요청을 날리지 않음.
    //image_file_name;
    if ([[JDFacade facade].loginUser.imageFileName isEqualToString:_ivc.selectedIcon.imageFileName]) {
        [[JDFacade facade] alert:NSLocalizedString(@"프로필 이미지를 선택해주세요", @"프로필 이미지를 선택해주세요")];
        return;
    }
    [self requestChangeMemberIcon];
}

- (void)btnCancelTouched:(id)sender {
    [self closeChildViewController:_ivc completionHandler:nil];
}


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


@end
