//
//  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 "CustomAlertView.h"
//#import "MobilesOverViewController.h"
//#import "InvitationListViewController.h"


@interface LoginViewController () <CustomTextFieldDelegate> {
}
@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:^(id label) {
        [self lblSignUpTouched];
    }];

    [_lblFindId addTouchEventHandler:^(id label) {
        [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;

    _chkAutoLogin.checked = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_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,
                            @"device_hostname": [JDFacade facade].deviceHostName ? [JDFacade facade].deviceHostName : 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
    NSString *authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
    
    [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,
                                @"device_hostname": [JDFacade facade].deviceHostName ? [JDFacade facade].deviceHostName : ksEmptyString};

    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)requestAuthMail {
    //parameters
    NSDictionary *parameter = @{@"email_id": [JDFacade facade].tmpEmailId};
    
    NSString *path = [NSString stringWithFormat:API_POST_AUTH_MAIL];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        JDJSONModel *result = (JDJSONModel *) responseObject;
        
        if (result) {//API 성공 ,
            [[JDFacade facade] toast:NSLocalizedString(@"인증 메일이 발송되었습니다", @"인증 메일이 발송되었습니다")];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[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:USDEF_APP_AUTO_LOGIN];
            [[JDFacade facade] storeObjectToKeychain:[JDFacade facade].loginUser.authToken forKey:USDEF_SESSION_AUTOTOKEN];
        } else {
            [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN];
        }

        [self actionAfterLogin];
    }
}

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

    if ([[JDFacade facade].loginUser.invitationsCount integerValue] > 0) {
        [self actionForInvitation];
        return;
    }

    [self actionAfterInvitaion];
}

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

//초대화면 액션이 종료된 후,
- (void)actionAfterInvitaion {
    
    //메인으로 이동
    [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 {

    NSString *message = [NSString stringWithFormat:@"%@에서\n인증 메일을 확인하세요\n\n메일을 확인할 수 없는 경우에는\n스팸 메일함을 확인해보세요", [JDFacade facade].tmpEmailId];
    CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"메일을 확인하세요" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재발송"];
    [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {//재발송
            [self requestAuthMail];
        }
    }];
}

- (void)gotoMainView {

//    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpCompleteViewController" storyboardName:@"SignUp"];
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MainViewController" storyboardName:@"Main"];
    
    [JDFacade facade].mainViewController = (MainViewController *)vc;
    [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:USDEF_APP_AUTO_LOGIN];
    [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN];
    
    [JDFacade facade].loginUser = 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:@"AgreementViewController" storyboardName:@"SignUp"];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)lblFindIdTouched {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ResetPwdViewController" storyboardName:@"SignUp"];
    [self presentViewController:vc animated:YES completion:nil];
}

#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
