//
//  JDJSONModel.h
//  kneet
//
//  Created by Jason Lee on 2/9/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "LoginModel.h"
#import "CypherUtil.h"
#import "NSData+AESCrypt.h"
#import "NSString-Addtions.h"

@implementation InvitationModel

@end

@implementation InvitationListModel

@end

@implementation QuizModel

-(BOOL)isUserEditQuiz
{
    BOOL result = NO;
    
    if ([_statusCode isEqualToIgnoreCase:@"1"]) {
        result = YES;
    }
    
    return result;
}

@end

@implementation QuizListModel

@end


@implementation HomeMemberModel

@end

@implementation HomeMemberListModel

- (BOOL)isRemainInvite {
    BOOL result = NO;
    
    if ([_limitCnt integerValue]-_ctrtGrpMemberList.count) {
        result = YES;
    }
    
    return result;
}

@end

@implementation MemberIconModel

@end

@implementation MemberIconListModel

@end

@implementation MobileDeviceListModel

@end

@implementation ContractGroupModel

@end

@implementation SignUpModel

@end

@implementation FindIdPwModel

@end


@implementation LoginModel

@synthesize memberId = _memberId, homegrpId = _homegrpId, newEmailId = _newEmailId, modeChange = _modeChange, noticeReadTime = _noticeReadTime, personalNoticeReadTime = _personalNoticeReadTime;


//+ (JSONKeyMapper *)keyMapper {
//
//    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
//
//    //Self
//    [dictionary setValue:@"lang" forKey:@"lang"];
//    [dictionary setValue:@"emailId" forKey:@"email_id"];
//    [dictionary setValue:@"authToken" forKey:@"auth_token"];
//
//    [dictionary setValue:@"lang" forKey:@"lang"];
//    [dictionary setValue:@"emailId" forKey:@"email_id"];
//    [dictionary setValue:@"authToken" forKey:@"auth_token"];
//    [dictionary setValue:@"member" forKey:@"member"];
//    [dictionary setValue:@"timezoneId" forKey:@"timezone_id"];
//    [dictionary setValue:@"timezone" forKey:@"timezone"];
//    [dictionary setValue:@"countryCode" forKey:@"country_code"];
//    [dictionary setValue:@"memberId" forKey:@"member_id"];
//    [dictionary setValue:@"serviceId" forKey:@"service_id"];
//    [dictionary setValue:@"imageFileName" forKey:@"image_file_name"];
//    [dictionary setValue:@"nickname" forKey:@"nickname"];
//    [dictionary setValue:@"key" forKey:@"key"];
//    [dictionary setValue:@"homegrpId" forKey:@"homegrp_id"];
//    [dictionary setValue:@"homegrpList" forKey:@"homegrp_list"];
//
//    return [[JSONKeyMapper alloc] initWithDictionary:dictionary];
//}

- (void)setSelectedHomeHubID:(NSString *)selectedHomeHubID{
// TODO : 홈허브를 선택했을 경우 저장하는 기능 구현
    if([self isExistHomeHubID:selectedHomeHubID])
    {
        _selectedHomeHubID = selectedHomeHubID;
    }
}

- (NSString *)getSelectedHomeHubID {
// TODO : 홈허브 아이디를 선택했을 경우 저장된 홈허브 아이디를 가져오는 기능
    return _selectedHomeHubID;
}

-(void)setHomeHubID:(NSString *)homeHubID {
    if([self isExistHomeHubID:homeHubID])
    {
        if (![_selectedHomeHubID isEqualToString:homeHubID]) {
            _selectedHomeHubID = homeHubID;
        }
    }
}

-(NSString *)getHomeHubID {
    NSString *result = @"";
    
    DeviceModel *info = [self getHomeHub];
    if (info != nil) {
        result = info.deviceId;
    }
    return result;
}

-(DeviceModel *)getHomeHub:(NSString*)homeHubId {
    
    DeviceModel *result = nil;
    
    for (DeviceModel *info in _deviceList) {
        if ([info.deviceId isEqualToIgnoreCase:homeHubId]) {
            result = info;
            break;
        }
    }
    
    return result;
}

-(DeviceModel *)getHomeHub {

    DeviceModel *result = nil;
    
    if (![self isMultiHomeHub]) {

        for (DeviceModel *info in _deviceList) {
            result = info;
            break;
        }
        
//        if (_selectedHomeHubID == nil || [_selectedHomeHubID isEmptyString]) {
//            for (DeviceModel *info in _deviceList) {
//                result = info;
//                break;
//            }
//        }
        
    } else {
        
        for (DeviceModel *info in _deviceList) {
            if ([info.deviceId isEqualToIgnoreCase:_selectedHomeHubID]) {
                result = info;
                break;
            }
        }
    }

    return result;
}

- (BOOL)isExistHomeHubID:(NSString *)homeHubID {
    BOOL result = false;
    
    for (DeviceModel *info in _deviceList) {
        if([info.deviceId isEqualToIgnoreCase:homeHubID]) {
            result = true;
        }
    }
    
    return result;
}

- (BOOL)isMultiHomeHub {
    BOOL result = false;
    
    if (_deviceList.count > 1) {
        result = true;
    }
    
    return result;
}


- (BOOL)onlineHomeHubFromSelectedHub:(DeviceModel*)selectedHub {
    
    BOOL result = false;
    
    //멀티인경우
    if (_deviceList.count > 1) {
       
        
        for (DeviceModel *device in _deviceList) {
            
            if (selectedHub != nil) {
                
                if (EQUALS(selectedHub.deviceId, device.deviceId))
                    return device.isDeviceOnlined;
            }
            else {
                
                if (device.isDeviceOnlined)
                    return true;
            }
        }
    }
    //단일인 경우
    else {
        
        return [self getHomeHub].isDeviceOnlined;
    }
    
    return result;
}


- (BOOL)connectedHomeHubFromSelectedHub:(DeviceModel*)selectedHub {
    
    BOOL result = false;
    
    //멀티인경우
    if (_deviceList.count > 1) {

        for (DeviceModel *device in _deviceList) {
            
            if (selectedHub != nil) {
                
                if (EQUALS(selectedHub.deviceId, device.deviceId))
                    return device.isDeviceConn;
            }
            else {
                
                if (device.isDeviceConn)
                    return true;
            }
        }
    }
    //단일인 경우
    else {
        
        return [self getHomeHub].isDeviceConn;
    }
    
    return result;
}


- (void)setMemberId:(NSString *)memberId {
    _memberId = memberId;

    //사용자 아이디 리스트
    NSMutableArray *userList = [[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_USERID_LIST];

    BOOL isExist = NO;
    if (!userList) {
        userList = [[NSMutableArray alloc] init];

    } else {
        for (NSString *memberId in userList) {
            isExist = [_memberId isEqualToString:memberId];
            if (isExist) {
                break;
            }
        }
    }

    if (!isExist) {//기존에 없으면 추가함.
        [userList addObject:_memberId];
    }

    [[JDFacade facade] storeObjectToUserDefaults:userList forKey:USDEF_APP_USERID_LIST];
}

- (NSString *)emailId {
    if (!_emailId || [_emailId isEmptyString]) {
        _emailId = [JDFacade facade].tmpEmailId;
    }
    return _emailId;
}

//새 이메일 변경 시 - 체크를 위한 로컬 저장
- (NSString *)newEmailId {
    if (!_newEmailId) {
        _newEmailId = [self.localStorage objectForKey:USDEF_SESSION_NEW_EMAIL];
    }
    return _newEmailId ? _newEmailId : nil;
}

- (void)setNewEmailId:(NSString *)newEmailId {
    _newEmailId = newEmailId;

    //로컬 저장소에 저장
    [self.localStorage setObject:_newEmailId forKey:USDEF_SESSION_NEW_EMAIL];
    [self synchronizeLocalStorage];
}

- (NSString *)ctrtGrpId {
    return [self ctrtGrp].ctrtGrpId;
}

- (ContractGroupModel *)ctrtGrp {
    ContractGroupModel *result = nil;
    if ([_selectCtrtGrpId isEmptyString]) {
        result = _ctrtGrpList[0];
    }
    else {
        for (ContractGroupModel *groupInfo in _ctrtGrpList) {
            if ([groupInfo.ctrtGrpId isEqualToIgnoreCase:_selectCtrtGrpId]) {
                result = groupInfo;
            }
        }
    }
    
    return result;
}


- (NSString *)gradeCode {
    return [self ctrtGrp].gradeCode;
}

//모드 변경 저장
- (NSString *)modeChange {
    if (!_modeChange) {
        _modeChange = [self.localStorage objectForKey:USDEF_SESSION_MODE_CHANGE];
    }
    return _modeChange ? _modeChange : nil;
}

- (void)setModeChange:(NSString *)modeChange {
    _modeChange = modeChange;

    //로컬 저장소에 저장
    [self.localStorage setObject:_modeChange forKey:USDEF_SESSION_MODE_CHANGE];
    [self synchronizeLocalStorage];
}

//세션 - 공지 읽음 날짜 확인
- (NSString *)noticeReadTime {
    if (!_noticeReadTime) {
        _noticeReadTime = [self.localStorage objectForKey:USDEF_SESSION_NOTICE_READ_DATE];
    }
    return _noticeReadTime ? _noticeReadTime : nil;
}

- (void)setNoticeReadTime:(NSString *)noticeReadTime {
    _noticeReadTime = noticeReadTime;
    
    //로컬 저장소에 저장
    [self.localStorage setObject:_noticeReadTime forKey:USDEF_SESSION_NOTICE_READ_DATE];
    [self synchronizeLocalStorage];
}


//세션 - 알림 읽음 날짜 확인
- (NSString *)personalNoticeReadTime {
    if (!_personalNoticeReadTime) {
        _personalNoticeReadTime = [self.localStorage objectForKey:USDEF_SESSION_PUSH_READ_DATE];
    }
    return _personalNoticeReadTime ? _personalNoticeReadTime : nil;
}

- (void)setPersonalNoticeReadTime:(NSString *)personalNoticeReadTime {
    _personalNoticeReadTime = personalNoticeReadTime;
    
    //로컬 저장소에 저장
    [self.localStorage setObject:_personalNoticeReadTime forKey:USDEF_SESSION_PUSH_READ_DATE];
    [self synchronizeLocalStorage];
}

- (NSInteger)level {
    
    _level = 0;
    if ([[self gradeCode] isEqualToString:KNEET_MEMBER_MASTER]) {
        _level = 90;
    } else if ([[self gradeCode] isEqualToString:KNEET_MEMBER_SIMPLE]) {
        _level = 10;
    }

    return _level;
}

// TODO: 홈그룹 온라인 / 보유 여부 로직 변경하기
- (BOOL)isHomehubOnline {
    BOOL result = YES;
//    for (DeviceModel *deviceInfo in _deviceList) {
//        NSLog(@"Device Info : %@", deviceInfo);
//        if (deviceInfo.isDeviceOnlined && deviceInfo.isDeviceConn) {
//            result = YES;
//            break;
//        }
//    }
    return result;
}

- (BOOL)hasHomeHub {
    
    BOOL result = YES;
//    for (DeviceModel *deviceInfo in _deviceList) {
//        if (deviceInfo.deviceId && ![deviceInfo.deviceId isEmptyString]) {
//            result = YES;
//            break;
//        }
//    }
    
    return result;
}

-(NSString *)authorization
{
//    NSString *result = @"asura77:1f6bafe0801d52b557fc7b5277cb878bc36e54987b6eec036e713b1229096117";
    NSString *result = nil;
    if(_memberId !=nil && _authToken != nil)
    {
        result= [[NSString stringWithFormat:@"%@:%@", _memberId, _authToken] base64Enc];
    }

    return result;
}


#pragma mark - about Location Settings
//로컬 저장소
- (NSMutableDictionary *)localStorage {
    if (!self.memberId)
        return nil;

    if (!_localStorage) {
        NSString *encryptedKey = [CypherUtil AES128Encrypt:self.memberId WithKey:self.memberId];
        _localStorage = [[JDFacade facade] objectForKeyFromUserDefaults:encryptedKey];

        if (!_localStorage) {//저장된 정보가 없을 경우,
            _localStorage = [[NSMutableDictionary alloc] init];
        }
    }
    return _localStorage;
}

- (void)synchronizeLocalStorage {

    if (!self.memberId)
        return;

    NSString *encryptedKey = [CypherUtil AES128Encrypt:self.memberId WithKey:self.memberId];
    [[JDFacade facade] storeObjectToUserDefaults:self.localStorage forKey:encryptedKey];
}



@end
