//
//  LoginViewController.m
//  kneet
//
//  Created by Jason Lee on 2/4/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//

@import QuartzCore;

#import "RequestHandler.h"
#import "CustomTextField.h"
#import "CustomButton.h"

#import "JDJSONModel.h"
#import "LoginModel.h"

#import "LoginViewController.h"
#import "CustomLabel.h"
#import "CustomCheckBox.h"
#import "KeychainItemWrapper.h"
#import "NewMobileViewController.h"
#import "ValidateUtil.h"
//#import "MobilesOverViewController.h"
//#import "InvitationListViewController.h"


@interface LoginViewController () <CustomTextFieldDelegate> {
    KeychainItemWrapper *_keychainItemWrapper;
}
@end


#pragma mark - Class Definition

@implementation LoginViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
//    

    _txtEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtPasswd.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtPasswd.secureTextEntry = YES;

    _txtEmail.keyboardType = UIKeyboardTypeEmailAddress;
    _txtPasswd.keyboardType = UIKeyboardTypeDefault;

    _txtEmail.returnKeyType = UIReturnKeyDone;
    _txtPasswd.returnKeyType = UIReturnKeyDone;

    _txtPasswd.delegate = self;

    [_lblSignUp addTouchEventHandler:^{
        [self lblSignUpTouched];
    }];

    [_lblFindId addTouchEventHandler:^{
        [self lblFindIdTouched];
    }];
    
    //Localization
    [_chkAutoLogin setTitle:NSLocalizedString(@"자동 로그인", @"자동 로그인") forState:UIControlStateNormal];
    _txtEmail.placeholder = NSLocalizedString(@"enter your email", @"enter your email");
    _txtPasswd.placeholder = NSLocalizedString(@"enter your password", @"enter your password");
    _lblSignUp.text = NSLocalizedString(@"회원가입", @"회원가입");
    _lblFindId.text = NSLocalizedString(@"ID/PW찾기", @"ID/PW찾기");
}

- (void)prepareViewDidLoad {
    //FIXME : 로그아웃 처리
    [RequestHandler handler].authorization = nil;
    [RequestHandler handler].homegrpId = nil;

    _chkAutoLogin.checked = [[[JDFacade facade] objectForKeyFromUserDefaults:USER_DEF_AUTO_LOGIN] boolValue];
    if (_chkAutoLogin.checked) {
        [self requestAutoLogin];
    }
}

#pragma mark - Main Logic

- (void)requestLogin {
    NSDictionary *param = @{@"email_id": _txtEmail.text,
                            @"password": _txtPasswd.text,
                            @"service_id": MOBILE_SERVICE_ID,
                            @"os_type": MOBILE_DEVICE_TYPE,
                            @"device_sn": [JDFacade facade].deviceUUID,
                            @"device_name": [CommonUtil deviceName],
                            @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString};

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:API_POST_SIGN_IN parameters:param modelClass:[LoginModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        LoginModel *loginInfo = (LoginModel *)responseObject;

        if (loginInfo) {//API 성공 ,함
            [self actionForLoginSucceed:loginInfo];

        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;

        if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_EMAIL]) {//이메일 아이디 인증이 안 된 계정
            [self actionForWaiting];
        } else if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_DEVICE]) {//새로운 단말 인증 필요
            [self actionForNeedsRegisteringNewDevice:error.nickname];
        } else if ([error.errorCode isEqualToString:API_RESPONSE_MOBILES_OVER]) {//단말 초과
            [self actionForMobilesOver:error.deviceList];
        } else {
            [[JDFacade facade] alert:error.errorMessage];
        }
    }];
}

//자동로그인 요청
- (void)requestAutoLogin {

    //parameters
    if (!_keychainItemWrapper) {
        _keychainItemWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:USER_DEF_AUTOTOKEN accessGroup:nil];
    }

    NSString *authToken = [_keychainItemWrapper objectForKey:(__bridge id)(kSecAttrAccount)];
    [RequestHandler handler].authorization = authToken;
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, authToken);

    NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID,
                                @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
                                @"os_type": MOBILE_DEVICE_TYPE};

    NSString *path = [NSString stringWithFormat:API_GET_SIGN_IN_AUTO];

    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[LoginModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        LoginModel *loginInfo = (LoginModel *)responseObject;

        if (loginInfo) {//API 성공 ,함
            [self actionForLoginSucceed:loginInfo];

        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;

        if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_DEVICE]) {//새로운 단말 인증 필요
            [self actionForNeedsRegisteringNewDevice:error.nickname];
        } else {
            [[JDFacade facade] alert:error.errorMessage];
        }
    }];

}

//로그인 이후 처리.
- (void)actionForLoginSucceed:(LoginModel *)loginInfo {

    if (loginInfo) {//API 성공함
        [JDFacade facade].loginUser = loginInfo;
        [JDFacade facade].tmpEmailId = [JDFacade facade].loginUser.emailId;

        if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].loginUser.newEmailId]) {//이메일 변경 요청 중
            [JDFacade facade].loginUser.newEmailId = ksEmptyString;
        }

        [RequestHandler handler].authorization = loginInfo.authToken;

        if (_chkAutoLogin.checked) {//자동로그인 설정 시, 인증 토큰 저장

            [[JDFacade facade] storeObjectToUserDefaults:@(_chkAutoLogin.checked) forKey:USER_DEF_AUTO_LOGIN];

            if (!_keychainItemWrapper) {
                _keychainItemWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:USER_DEF_AUTOTOKEN accessGroup:nil];
            }
            // save AuthToken in keychain
            [_keychainItemWrapper setObject:loginInfo.authToken forKey:(__bridge id)(kSecAttrAccount)];
        }

        [self actionAfterLogin];
    }
}

//홈그룹 체크 및 대시보드 이동
- (void)actionAfterLogin {

    if ([JDFacade facade].loginUser.invitationList && [JDFacade facade].loginUser.invitationList.count) {
        [self actionForInvitation];
        return;
    }

    [self actionAfterInvitaion];
}

//초대알림 화면으로 이동
- (void)actionForInvitation {
    [[JDFacade facade] loadInvitationView];
}

//초대화면 액션이 종료된 후,
- (void)actionAfterInvitaion {
    
    if (![JDFacade facade].loginUser.homegrpList || [JDFacade facade].loginUser.homegrpList.count <= 0) {//홈그룹이 없을 경우, 홈 시작페이지로 이동함
        [[JDFacade facade] gotoStartHome:NO];
        return;
    }

//    if (![JDFacade facade].loginUser.homegrpId || [[JDFacade facade].loginUser.homegrpId isEmptyString]) {//저장된 홈 그룹이 없으면 디폴트 홈을 설정함
//        HomeGroupModel *homeGroup = [JDFacade facade].loginUser.homegrpList[0];
//        [JDFacade facade].loginUser.homegrpId = homeGroup.homegrpId;
//    }

    for (HomeGroupModel *homeGroup in [JDFacade facade].loginUser.homegrpList) {
        if ([[JDFacade facade].loginUser.homegrpId isEqualToString:homeGroup.homegrpId]) {//동일한 홈그룹을 현재 홈그룹으로 설정함.
            [JDFacade facade].loginHomeGroup = homeGroup;
            break;
        }
    };
    
    if (![JDFacade facade].loginHomeGroup) {//저장된 홈 그룹이 없거나, 일치하는 홈그룹이 없을 경우, 최상위 홈을 현재 홈으로 설정
        [JDFacade facade].loginHomeGroup = [JDFacade facade].loginUser.homegrpList[0];
    }

    //메인으로 이동
    [self gotoMainView];
}

//새로운 단말 인증 필요 - 화면 이동
- (void)actionForNeedsRegisteringNewDevice:(NSString *)nickname {

    NewMobileViewController *vc = (NewMobileViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"NewMobileViewController" storyboardName:@"SignUp"];
    vc.checkedAutoLogin = _chkAutoLogin.checked;
    vc.nickname = nickname;
    [[JDFacade facade] presentViewControllerByPush:vc pvc:self];
}

//단말대수 초과
- (void)actionForMobilesOver:(NSArray<MobileDeviceModel> *)deviceList {
    //SHA-2
}

//인증대기중 - 화면 이동
- (void)actionForWaiting {

    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpInfoViewController" storyboardName:@"SignUp"];
    UINavigationController *nc = [[UINavigationController alloc] init];
    nc.viewControllers = @[vc];

    [[JDFacade facade] presentViewControllerByPush:nc pvc:self];
}

- (void)gotoMainView {

//    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpCompleteViewController" storyboardName:@"SignUp"];
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MainViewController" storyboardName:@"Main"];
    [JDFacade facade].appDelegate.window.rootViewController = vc;
}

- (void)requestLogout {
    //parameters
    NSString *path = [NSString stringWithFormat:API_POST_SIGN_OUT];

    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[JDJSONModel class] completion:^(id responseObject) {
        [self actionAfterLogout];

    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)actionAfterLogout {

    //자동 로그인 설정 - 취소
    [[JDFacade facade] storeObjectToUserDefaults:@NO forKey:USER_DEF_AUTO_LOGIN];

    if (!_keychainItemWrapper) {
        _keychainItemWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:USER_DEF_AUTOTOKEN accessGroup:nil];
    }
    // save AuthToken in keychain
    [_keychainItemWrapper setObject:nil forKey:(__bridge id)(kSecAttrAccount)];

    [JDFacade facade].loginUser = nil;
    [JDFacade facade].loginHomeGroup = nil;
    
    //root view 변경
    [JDFacade facade].appDelegate.window.rootViewController = self;
}

#pragma mark - UI Events
- (IBAction)btnLogInTouched:(id)sender {

#ifdef DEBUG_MODE
    if ([_txtEmail.text isEmptyString]) {
        _txtEmail.text = @"gojeong@ntels.com";
    }

    if ([_txtPasswd.text isEmptyString]) {
        _txtPasswd.text = @"goj132!#@";
    }
#endif

    if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeEmail title:@"이메일" ]) {
        return;
    }

    if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeEmail title:@"비밀번호" ]) {
        return;
    }

    [JDFacade facade].tmpEmailId = _txtEmail.text;
    [JDFacade facade].tmpPassword = _txtPasswd.text;

    [self requestLogin];
}



- (void)lblSignUpTouched {

    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpViewController" storyboardName:@"SignUp"];

    UINavigationController *nc = [[UINavigationController alloc] init];
    nc.viewControllers = @[vc];

    [[JDFacade facade] presentViewControllerByPush:nc];
}

- (void)lblFindIdTouched {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ResetPwdViewController" storyboardName:@"SignUp"];

    UINavigationController *nc = [[UINavigationController alloc] init];
    nc.viewControllers = @[vc];

    [[JDFacade facade] presentViewControllerByPush:nc];
}

#pragma mark - CustomTextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField isEqual:_txtPasswd]) {
        [self btnLogInTouched:nil];
    }

    return YES;
}


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


@end
