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

#import "VankeCommonModel.h"
#import "VankeConfig.h"

#pragma mark -

@implementation VankeCommonModel

DEF_SINGLETON(VankeCommonModel)

- (void) saveLoginInfo: (LoginResponseData*) info password: (NSString*) password {
    if (nil == info) {
        [self removeLoginInfo];
        return;
    }
    
    [self userDefaultsWrite:[info objectToDictionary] forKey:KEY_CURRENT_USER_INFO];
    [self keychainWrite:password forKey:KEY_CURRENT_USER_PWD];
}


- (LoginResponseData*) getLoginInfo {
    NSDictionary *dict = [self userDefaultsRead:KEY_CURRENT_USER_INFO];
    if (nil == dict) {
        return nil;
    }
    
    return [LoginResponseData objectFromDictionary: dict];
}

- (void) removeLoginInfo {
    [self userDefaultsRemove:KEY_CURRENT_USER_INFO];
    [self keychainDelete:KEY_CURRENT_USER_PWD];
}

- (User*) currentUser {
    LoginResponseData *data = [self getLoginInfo];
    if (nil != data) {
        return [data getUser];
    } else {
        return nil;
    }
}

- (Enterpirse*) currentEnt {
    LoginResponseData *data = [self getLoginInfo];
    if (nil != data) {
        return [data getEnterprise];
    } else {
        return nil;
    }
}

-(NSArray*) getAuthOrgs {
    LoginResponseData *data = [self getLoginInfo];
    if (nil != data && nil != data.authorizedOrgs) {
        NSArray *sortedArray = [data.authorizedOrgs sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSComparisonResult result = [((AuthorizedOrg*) obj1).code compare:((AuthorizedOrg*) obj2).code];
            return result;
        }];
        return sortedArray;
    } else {
        return nil;
    }
}

- (NSString*) currentUserPwd {
    return [self keychainRead:KEY_CURRENT_USER_PWD];
}

-(BOOL) curUserIsTenant {
    LoginResponseData *loginInfo = [self getLoginInfo];
    return [USER_POSITION_TENANT eq: loginInfo.position];
}

-(BOOL) curUserIsHQ {
    LoginResponseData *loginInfo = [self getLoginInfo];
    return [USER_POSITION_HQ eq: loginInfo.position];
}

-(BOOL) curUserIsStore {
    LoginResponseData *loginInfo = [self getLoginInfo];
    return [USER_POSITION_STORE eq: loginInfo.position];
}

@end
