//
//  ICRModifyPwdViewController.m
//  XFFruit
//
//  Created by Lili Wang on 15/4/3.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

typedef NS_ENUM(NSUInteger, _InputTextTag) {
    kInputOldPwd = 0,
    kInputNewPwd,
    kInputConfirmPwd,
};

typedef NS_ENUM(NSInteger, ChangePWDError) {
    kNoError = 0,
    kOldPwdNotMatch,
    kNewPwdIsEqualToOld,
    kNewPwdILLegal,
    kConfirmPwdIsNotMatchNewPwd,
    kConfirmPwdILLegal,
    
    kCustomError,
};

static NSString * const ChangePWDErrorDescription[] = {
    [ kNoError ]                    = @"",
    [ kOldPwdNotMatch ]             = @"Old password is not correct.",
    [ kNewPwdIsEqualToOld ]         = @"New password is equal to old.",
    [ kNewPwdILLegal ]              = @"New password is illegal.",
    [ kConfirmPwdIsNotMatchNewPwd ] = @"Confirm password is not equal to new.",
    [ kConfirmPwdILLegal ]          = @"Confirm password is illegal."
};

static NSString *ChangePwdCellID = @"ChangePwdCellID";

#import "ICRModifyPwdViewController.h"
#import "IBTTextFieldCell.h"
#import "IBTTableView.h"

@interface ICRModifyPwdViewController ()
<
UITableViewDataSource,
UITextFieldDelegate
>
{
    BOOL m_bIsNewPwdLegal;
    BOOL m_bIsConfirmPwdLegal;
    
    BOOL m_bNewIsEqualToOld;
    BOOL m_bNewIllegal;
    BOOL m_bConfirmNotMatch;
    BOOL m_bConfirmIllegal;
    
    ChangePWDError m_eLocalError;
}
@property (weak, nonatomic) UIButton *m_submitBtn;
@property (strong, nonatomic) UILabel *m_indicatorLabel;
@property (weak, nonatomic) UITextField *m_oldPwdTextF;
@property (weak, nonatomic) UITextField *m_newPwdTextF;
@property (weak, nonatomic) UITextField *m_confirmPwdTextF;

@property (strong, nonatomic) NSString *m_nsOldPassword;
@property (strong, nonatomic) NSString *m_nsNewPassword;
@property (strong, nonatomic) NSString *m_nsConfirmPassword;

@property (strong, nonatomic) IBTTableView *m_tableView;

@property (strong, nonatomic) IBTUIView    *m_indicatorView;
@end

@implementation ICRModifyPwdViewController

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

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self updateSubmitButtonForSending:NO];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self addTextFieldObserver];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [self removeTextFieldObserver];
    
    [super viewWillDisappear:animated];
}

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

#pragma mark - Action
- (void)onSubmitAction:(id)sender {
    [self updateSubmitButtonForSending:YES];

    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    __weak typeof(self)weakSelf = self;
    [httpCtrl doChangePassword:[_m_nsOldPassword uppercaseMD5String]
                   newPassword:[_m_nsNewPassword uppercaseMD5String]
                       success:^(id data) {
                           __strong __typeof(weakSelf)strongSelf = weakSelf;
                           [[ICRUserUtil sharedInstance] updatePassword:_m_nsNewPassword];
                           [strongSelf updateSubmitButtonForSending:NO];
                           [self.navigationController popViewControllerAnimated:YES];
                       }
                       failure:^(id data) {
                           __strong __typeof(weakSelf)strongSelf = weakSelf;
                           m_eLocalError = kCustomError;
                           [strongSelf showTopMessage:data];
                           [strongSelf updateSubmitButtonForSending:NO];
                       }];
}

#pragma mark - Private Method
- (void)setupSubviews {
    self.title = [IBTCommon localizableString:@"Change Password"];
    
    self.m_tableView = [[IBTTableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _m_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [_m_tableView registerClass:[IBTTextFieldCell class] forCellReuseIdentifier:ChangePwdCellID];
    _m_tableView.dataSource = self;
    
    [self.view addSubview:_m_tableView];
    
    UIButton *btn = nil;
    UIView *tableFooter = [_m_tableView buttonViewWithTitle:[IBTCommon localizableString:@"Submit"]
                                                      color:nil
                                                     topGap:32
                                                    pointer:&btn
                                                     target:self
                                                     action:@selector(onSubmitAction:)];
    _m_tableView.tableFooterView = tableFooter;
    self.m_submitBtn = btn;
}
- (void)showLocalInfoWithErrror:(ChangePWDError)newError {
    if (m_eLocalError == newError) {
        return;
    }
    
    m_eLocalError = newError;
    
    [self showTopMessage:[IBTCommon localizableString:ChangePWDErrorDescription[ m_eLocalError ]]];
}
- (void)updateSubmitButtonForSending:(BOOL)isSending {
    _m_submitBtn.enabled = m_bIsNewPwdLegal && m_bIsConfirmPwdLegal;
    
    if (_m_submitBtn.enabled) {
        [self showLocalInfoWithErrror:kNoError];
    }
    
    _m_submitBtn.userInteractionEnabled = !isSending;
    [_m_submitBtn setTitle:[IBTCommon localizableString:isSending ? @"Submiting..." :@"Submit"]
                  forState:UIControlStateNormal];
}

- (BOOL)checkNewPassword {
    m_bNewIsEqualToOld = [self.m_nsNewPassword isEqualToString:self.m_nsOldPassword];
    
    if (m_bNewIsEqualToOld) {
        return m_bIsNewPwdLegal = NO;
    }
    
    m_bNewIllegal = ![IBTCommon isLegalString:_m_nsNewPassword WithRegex:IBT_PASSWORD_REGEX];
    
    if (m_bNewIllegal) {
        return m_bIsConfirmPwdLegal = NO;
    }
    
    return m_bIsNewPwdLegal = YES;
}

- (BOOL)checkConfirmPassword {
    m_bConfirmNotMatch = ![self.m_nsConfirmPassword isEqualToString:self.m_nsNewPassword];
    
    if (m_bConfirmNotMatch) {
        
        return m_bIsConfirmPwdLegal = NO;
    }
    
    m_bConfirmIllegal = ![IBTCommon isLegalString:_m_nsConfirmPassword WithRegex:IBT_PASSWORD_REGEX];
    
    if (m_bConfirmIllegal) {
        
        return m_bIsConfirmPwdLegal = NO;
    }
    
    return m_bIsConfirmPwdLegal = YES;
}

- (void)showTopMessage:(NSString *)message {
    if (![message isKindOfClass:[NSString class]]) {
        return;
    }
    
    
    if ([message length] == 0) {
        _m_tableView.tableHeaderView = nil;
        return;
    }
    
    if (!_m_indicatorView) {
        self.m_indicatorView = [[IBTUIView alloc] init];
        _m_indicatorView.backgroundColor = [UIColor clearColor];
        self.m_indicatorLabel = [[UILabel alloc] init];
        _m_indicatorLabel.textColor = [UIColor redColor];
        _m_indicatorLabel.textAlignment = NSTextAlignmentLeft;
        _m_indicatorLabel.font = [UIFont systemFontOfSize:17];
        _m_indicatorLabel.numberOfLines = 0;
        [_m_indicatorView addSubview:_m_indicatorLabel];
    }
    
    _m_indicatorLabel.text = message;
    
    CGFloat xPadding = 10;
    CGFloat yPadding = 5;
    CGFloat w = _m_tableView.width - 2 * xPadding;
    
    _m_indicatorLabel.frame = (CGRect){
        .origin.x = xPadding,
        .origin.y = yPadding,
        .size.width = w,
        .size.height = [UILabel getHeightWithText:_m_indicatorLabel.text
                                             font:_m_indicatorLabel.font
                                         andWidth:w]
    };
    
    
    CGFloat h = CGRectGetHeight(_m_indicatorLabel.frame) + 2 * yPadding;
    w = _m_tableView.width;
    
    if (IBT_IOS7_OR_LATER) {
        h = MAX(h-35, 1);
    }
    
    _m_indicatorView.frame = (CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = w,
        .size.height = h
    };
    
    _m_tableView.tableHeaderView = _m_indicatorView;
}

- (IBTTextFieldCell *)cellForInputTextTag:(_InputTextTag)tag {
    NSIndexPath *indexP = [NSIndexPath indexPathForRow:tag inSection:0];
    UITableViewCell *cell = [_m_tableView cellForRowAtIndexPath:indexP];
    IBTTextFieldCell *mCell = nil;
    if ([cell isKindOfClass:[IBTTextFieldCell class]]) {
        mCell = (IBTTextFieldCell *)cell;
    }
    
    return mCell;
}

#pragma mark - UITableViewDataSource

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:ChangePwdCellID forIndexPath:indexPath];
    
    [self configureCell:cell forRowAtIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
{
    IBTTextFieldCell *mCell = (IBTTextFieldCell *)cell;
    UITextField *inputTxtF = mCell.textField;
    inputTxtF.secureTextEntry = YES;
    inputTxtF.tag = indexPath.row;
    
    switch (indexPath.row) {
        case kInputOldPwd:
            mCell.textLabel.text = [IBTCommon localizableString:@"Old"];
            inputTxtF.placeholder = [IBTCommon localizableString:@"Required"];
            inputTxtF.text = _m_nsOldPassword;
            inputTxtF.delegate = self;
            inputTxtF.returnKeyType = UIReturnKeyNext;
            self.m_oldPwdTextF = inputTxtF;
            if ([_m_nsOldPassword length] > 0) {
                mCell.textIsIllegal = NO;
            }
            break;
        case kInputNewPwd:
            mCell.textLabel.text = [IBTCommon localizableString:@"New"];
            inputTxtF.placeholder = [IBTCommon localizableString:@"Required"];
            inputTxtF.text = _m_nsNewPassword;
            inputTxtF.delegate = self;
            inputTxtF.returnKeyType = UIReturnKeyNext;
            self.m_newPwdTextF = inputTxtF;
            if ([_m_nsNewPassword length] > 0) {
                mCell.textIsIllegal = ![self checkNewPassword];
            }
            break;
        case kInputConfirmPwd:
            mCell.textLabel.text = [IBTCommon localizableString:@"Confirm"];
            inputTxtF.placeholder = [IBTCommon localizableString:@"Required"];
            inputTxtF.text = _m_nsConfirmPassword;
            inputTxtF.delegate = self;
            inputTxtF.returnKeyType = UIReturnKeyDone;
            self.m_confirmPwdTextF = inputTxtF;
            if ([_m_nsConfirmPassword length] > 0) {
                mCell.textIsIllegal = ![self checkConfirmPassword];
            }
            break;
        default:
            break;
    }
}

#pragma mark - TextObserver
- (void)addTextFieldObserver {
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self
                   selector:@selector(inputTextEditChanged:)
                       name:UITextFieldTextDidChangeNotification
                     object:nil];
}

- (void)removeTextFieldObserver {
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter removeObserver:self
                          name:UITextFieldTextDidChangeNotification
                        object:nil];
}

- (void)inputTextEditChanged:(NSNotification *)obj{
    
    UITextField *textField = obj.object;
    
    IBTTextFieldCell *mCell = [self cellForInputTextTag:textField.tag];
    
    switch (textField.tag) {
        case kInputOldPwd:
        {
            self.m_nsOldPassword = textField.text;
            mCell.textIsIllegal = NO;
            
        }
            break;
        case kInputNewPwd:
        {
            self.m_nsNewPassword = textField.text;
            mCell.textIsIllegal = ![self checkNewPassword];
            
            if ([self.m_nsConfirmPassword length] > 0) {
                IBTTextFieldCell *confirmCell = [self cellForInputTextTag:kInputConfirmPwd];
                confirmCell.textIsIllegal = ![self checkConfirmPassword];
            }
            
        }
            break;
        case kInputConfirmPwd:
        {
            self.m_nsConfirmPassword = textField.text;
            mCell.textIsIllegal = ![self checkConfirmPassword];
            
        }
            break;
        default:
            break;
    }
    
    [self updateSubmitButtonForSending:NO];
}

#pragma mark - Keyboard Notification
- (void)keyboardWillShow:(NSNotification *)note {
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    [_m_tableView setContentInsetTop:_m_tableView.contentInset.top andBottom:CGRectGetHeight(keyboardBounds)];
    
    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note {
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    [_m_tableView setContentInsetTop:_m_tableView.contentInset.top andBottom:0];
    
    
    // commit animations
    [UIView commitAnimations];
}

@end
