
//
//  VankeUserModel.m
//  vanke
//
//  Created by xiaomi on 15/10/5.
//  Copyright © 2015年 gomore. All rights reserved.
//

#import "VankeUserModel.h"
#import "VankeUserLoginAPI.h"
#import "VankeConfig.h"
#import "VankeUtil.h"
#import "VankeCommonModel.h"

#pragma mark -

@implementation VankeUserModel

-(LoginResponse*) getServerResp {
    return (LoginResponse*) self.serverResp;
}

-(void) clear {
    self.serverResp = nil;
}

// 登录
-(void) login: (NSString*) userName password: (NSString*) password {
    [VankeUserLoginAPI cancel];
    
    VankeUserLoginAPI *api = [VankeUserLoginAPI api];
    
    @weakify(api);
    @weakify(self);
    
    api.userName = userName;
    api.password = password;
    api.authenticode = VANKE_AUTHENTI_CODE;
    
    // 清空结果
    self.serverResp = nil;
    
    api.whenSucceed = ^{
        @normalize(api);
        @normalize(self);
        
        if (api.sending) {
            [self sendUISignal:self.RELOADING];
        } else {
            if (api.succeed) {
                if (nil == api.serverResp) {
                    api.failed = YES;
                } else {
                    // save user
                    self.serverResp = api.serverResp;
                    [self saveLoginUser:password];
                }
            }
           [self sendUISignal:self.RELOADED];
        }
    };
    api.whenFailed = ^{
        @normalize(api);
        @normalize(self);
        
        [[VankeCommonModel sharedInstance] removeLoginInfo];
        self.serverResp = [LoginResponse initWith:NO message:nil == api.errorDesc? @"网络异常": api.errorDesc];
        [self sendUISignal:self.RELOADED];
    };
    api.whenCancelled = ^{
        @normalize(api);
        @normalize(self);
        
        [[VankeCommonModel sharedInstance] removeLoginInfo];
        self.serverResp = [LoginResponse initWith:NO message:nil == api.errorDesc? @"用户取消": api.errorDesc];
        [self sendUISignal:self.RELOADED];
    };

    [api send];
}

-(BOOL) canAutoLogin {
    return nil != [[VankeCommonModel sharedInstance] currentUser];
}

-(void) autoLogin {
    User *curUser = [[VankeCommonModel sharedInstance] currentUser];
    NSString *userName = curUser.code;
    NSString *password = [[VankeCommonModel sharedInstance] currentUserPwd];
    [self login:userName password:password];
}

- (void) saveLoginUser: (NSString*) password {
    LoginResponse *resp = [self getServerResp];
    if (nil == resp || nil == resp.data) {
        return;
    } else {
        [[VankeCommonModel sharedInstance] saveLoginInfo:resp.data password:password];
    }
}

-(void) cancel {
    [VankeUserLoginAPI cancel];
}

@end
