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

#import "IBTUIKit.h"
#import "VankeUtil.h"
#import "GEToast.h"
#import "IBTConstants.h"
#import "VankeBaseAPI.h"
#import "VankeCommonModel.h"

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"
#import "ICRAppMacro.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


DEF_NOTIFICATION( SUCC_LOGOUT )

ON_CREATE_VIEWS( signal )
{
    self.title = [IBTCommon localizableString:@"Change Password"];
    self.view.backgroundColor = [VankeUtil colorWithHexString:@"#f6f6f6"];
}

ON_WILL_APPEAR( signal )
{
    [self updateSubmitButtonForSending:NO];
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
    [self removeTextFieldObserver];
    [super viewWillDisappear:YES];
}

ON_DID_DISAPPEAR( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
    if (nil == self.m_tableView) {
        [self setupSubviews];
        [self addTextFieldObserver];
    }
}

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

#define ALERT_TAG 100

- (void)onSubmitAction:(id)sender {
    [self updateSubmitButtonForSending:YES];
    
    VankeBaseAPI *api = [VankeBaseAPI api];
    
    @weakify(api);
    @weakify(self);
    
    User *curUser = [[VankeCommonModel sharedInstance] currentUser];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *curTime = [dateFormatter stringFromDate:[NSDate date]];
    
    NSString *url = [NSString stringWithFormat:@"/user/change_password/%@", curUser.uuid];
    
    NSDictionary *queryParam = [NSDictionary dictionaryWithObjectsAndKeys:
                          curTime, @"time",
                          curUser.code, @"operId",
                          curUser.name, @"operName",
                          nil];
    NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:
                        [VankeUtil md5:_m_oldPwdTextF.text], @"oldPassword",
                         [VankeUtil md5:_m_newPwdTextF.text], @"newPassword",
                          nil];
    NSString *postData = [VankeUtil dictToJsonString: postDict];
    [api http_post:url].PARAM(queryParam).BODY(postData).TIMEOUT(10);
    
    api.whenSucceed = ^{
        @normalize(api);
        
        [GEToast hideProgress];
        NSLog(@"response: %@", api.responseString);
        
        VankeResponse *resp = [VankeResponse objectFromDictionary: api.responseJSONDictionary];
        if (![resp isOk]) {
            [self updateSubmitButtonForSending:NO];
            [GEToast showWithText:nil == resp.message ? @"网络异常" : resp.message bottomOffset:60.0f duration:2.0f];
        } else {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@""
                                                           message:@"操作成功，请重新登录！"
                                                          delegate:self
                                                 cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil];
            alert.tag = ALERT_TAG;
            [alert show];
        }
    };
    api.whenFailed = ^{
        @normalize(api);
        @normalize(self);
        
        [GEToast hideProgress];
        NSLog(@"response: %@", api.responseString);
        
        [self updateSubmitButtonForSending:NO];
        [GEToast showWithText:nil == api.errorDesc ? @"网络异常" : api.errorDesc bottomOffset:60.0f duration:2.0f];
    };
    
    [GEToast showProgress:self.view];
    [api send];
}

#pragma marks -- UIAlertViewDelegate --

//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == ALERT_TAG) {
        [[VankeCommonModel sharedInstance] removeLoginInfo];
        [self postNotification:self.SUCC_LOGOUT];
        [self.stack popBoardAnimated:NO];
    }
}

#pragma mark - Private Method
- (void)setupSubviews {
    CGRect rect = self.view.bounds;
    rect.origin.y = 30.0f;
    self.m_tableView = [[IBTTableView alloc] initWithFrame:rect style:UITableViewStyleGrouped];
    _m_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [_m_tableView registerClass:[IBTTextFieldCell class] forCellReuseIdentifier:ChangePwdCellID];
    _m_tableView.dataSource = self;
    
    UIButton *btn = nil;
    UIView *tableFooter = [_m_tableView buttonViewWithTitle:[IBTCommon localizableString:@"Submit"]
                                                      color:ICR_ORANGE_BTN_COLOR
                                                     topGap:30
                                                    pointer:&btn
                                                     target:self
                                                     action:@selector(onSubmitAction:)];
    [btn.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    _m_tableView.tableFooterView = tableFooter;
    self.m_submitBtn = btn;
    _m_submitBtn.enabled = NO;
    _m_submitBtn.userInteractionEnabled = NO;
    
    [self.view addSubview:_m_tableView];
}

- (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 = ![VankeUtil isBlankString:_m_oldPwdTextF.text] && 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
