//
//  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 "CustomImageView.h"
#import "PwdPopupView.h"
#import "QuizSetViewController.h"
#import "TempPwViewController.h"
#import "SettingsNumChangeViewController.h"

//#import "MobilesOverViewController.h"
//#import "InvitationListViewController.h"

/**
 
ID / PW Input Box Text Color
    - 기본     : kUITextColor01
    - Hint    : kUITextColor03
    - Disable : kUITextColor06
 
로그인 유지 / 아이디 저장 Text Color : kUITextColor01
 
아이디 찾기 / 비밀번호 찾기 / 회원가입하기 Text Color
    - 아이디 찾기,비밀번호 찾기 : kUITextColor01
    - 회원가입 하기          : kUITextColor04

**/

@interface LoginViewController () <CustomTextFieldDelegate,dismissQuizViewDelegate> {
}
@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 {
    
    _btnLogin.enabled = NO;
    
    [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_active"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_disable"] forState:UIControlStateDisabled capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    [self.lblFindId setHidden:YES];
    
    CGRect screen = [UIScreen mainScreen].bounds;
    if (screen.size.height == 480) {//iphone4s
        [_imgvBg setImage:[UIImage imageNamed:@"img_login_bg_4inch"]];
        
    } if (screen.size.height == 667.0f) {//iphone6

        _constraintLeftPadding.constant *= 1.25;
        _constraintRightPadding.constant *= 1.25;
        
    } else if (screen.size.height == 736.0f) {//iphone6 plus
        
        _constraintLeftPadding.constant *= 1.5;
        _constraintRightPadding.constant *= 1.5;
    }
    
//    [self.view layoutIfNeeded];
    
    _txtEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtPasswd.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtPasswd.secureTextEntry = YES;

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

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

    
    _txtPasswd.delegate = self;
    _txtEmail.delegate = self;

    //Localization
    [_chkAutoLogin setTitle:NSLocalizedString(@"로그인 유지", @"로그인 유지") forState:UIControlStateNormal];
    [_chkIdSave setTitle:NSLocalizedString(@"아이디 저장", @"아이디 저장") forState:UIControlStateNormal];
    
    _txtEmail.placeholder = NSLocalizedString(@"아이디", @"아이디");
    _txtPasswd.placeholder = NSLocalizedString(@"비밀번호", @"비밀번호");
    
    _lblSignUp.text = NSLocalizedString(@"회원가입", @"회원가입");
    _lblFindId.text = NSLocalizedString(@"아이디/비번찾기", @"아이디/비번찾기");
    
    
//    [_lblSignUp setUnderLine:_lblSignUp.text];
    [_lblSignUp addTouchEventHandler:^(id label) {
        [self lblSignUpTouched];
    }];
    
    [_lblFindId setUnderLine:_lblFindId.text];
    [_lblFindId addTouchEventHandler:^(id label) {
        [self lblFindIdTouched];
    }];
}

- (void)prepareViewDidLoad {
    
    [RequestHandler handler].authorization = nil;
    
    BOOL autoLogin = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_AUTO_LOGIN] boolValue];
    BOOL idSave = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_SAVE_ID] boolValue];
    
    _chkAutoLogin.checked = [[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_AUTO_LOGIN] != nil ? autoLogin : YES;
    
    _chkIdSave.checked = [[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_SAVE_ID] != nil ? idSave : YES;
    
    if (autoLogin) {
        [self requestAutoLogin];
//        _txtEmail.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
//        _txtPasswd.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_PWD];
//        
//        [self btnLogInTouched:_btnLogin];
    }
    
    if (idSave) {
        _txtEmail.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
    }
        
}

#pragma mark - Main Logic

- (void)requestLogin {
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_LOGIN];
    NSDictionary *param = @{@"member_id": [_txtEmail.text trim],
                            @"password": [_txtPasswd.text trim],
                            @"os_type": MOBILE_DEVICE_TYPE,
                            @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString};
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[LoginModel class] isLoading:YES];


}

//자동로그인 요청
- (void)requestAutoLogin {;
    
    LoginModel *tmpInfo = [[LoginModel alloc] init];
    tmpInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
    tmpInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_AUTO_LOGIN];
    NSDictionary *param = @{@"Authorization": tmpInfo.authorization,
                                @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
                                @"os_type": MOBILE_DEVICE_TYPE};
    
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[LoginModel class] isLoading:YES];

//    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].loginUser.gradeCode = KNEET_MEMBER_MASTER;
//        [JDFacade facade].loginUser.level = 90;
        
        NSLog(@"loginUser : %@", [JDFacade facade].loginUser);
        
        if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].tmpEmailId]) {
            [JDFacade facade].tmpEmailId = ksEmptyString;
        }

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

        [RequestHandler handler].authorization = loginInfo.authorization;

        
        [[JDFacade facade] storeObjectToUserDefaults:@(_chkAutoLogin.checked) forKey:USDEF_APP_AUTO_LOGIN];
        [[JDFacade facade] storeObjectToUserDefaults:@(_chkIdSave.checked) forKey:USDEF_APP_SAVE_ID];
        
        if (_chkAutoLogin.checked) {//자동로그인 설정 시, 인증 토큰 저장
            [[JDFacade facade] storeObjectToKeychain:loginInfo.memberId forKey:USDEF_SESSION_LOGIN_ID];
            [[JDFacade facade] storeObjectToKeychain:loginInfo.authToken forKey:USDEF_SESSION_AUTOTOKEN];
        } else {
            [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN];
            [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_PWD];
            if (!_chkIdSave.checked) {
                [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID];
            }
        }
        
        if (_chkIdSave.checked) {
            
            [[JDFacade facade] storeObjectToKeychain:[_txtEmail.text trim] forKey:USDEF_SESSION_LOGIN_ID];
        } else {
            if (!_chkAutoLogin.checked) {
                [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID];
            }

        }

         [self actionAfterLogin];
    }
}

//퀴즈 설정 메뉴 dismiss 시
- (void)dismissQuizView {
     [self gotoMainView];
}

//홈그룹 체크 및 대시보드 이동
- (void)actionAfterLogin {
    
    if ([[JDFacade facade].loginUser.quiz isEqualToString:@""]) {
        QuizSetViewController *vc = (QuizSetViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"QuizSetViewController" storyboardName:@"Main"];
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
        return;
    }
    
    if ([[JDFacade facade].loginUser.invitationsCount integerValue] > 0) {
        [[JDFacade facade] loadInvitationView];
        return;
    }

    NSLog(@"temp : %d", [JDFacade facade].loginUser.tempPasswordYn && [[JDFacade facade].loginUser.tempPasswordYn boolValue]);
    
    //로그인 성공 후
    //1. 임시 비밀번호 발급 Y인 경우 체크 후 이동
    if ([JDFacade facade].loginUser.tempPasswordYn && [[JDFacade facade].loginUser.tempPasswordYn boolValue]) {
        
        TempPwViewController *vc = (TempPwViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"TempPwSetViewController" storyboardName:@"SignUp"];
        [self presentViewController:vc animated:YES completion:nil];
        return;
    }

    //2.휴대폰 번호 유효성 체크후 이동
    if ([JDFacade facade].loginUser.phoneAuthYn && ![[JDFacade facade].loginUser.phoneAuthYn boolValue]) {
        
        [self precessPhoneAuth];
        return;
    }
    
     [self gotoMainView];
}


- (void)precessPhoneAuth {
    
    [[JDFacade facade] confirmTitle:@"알림"
                            message:@"현재 사용 중인 휴대폰 번호로 계정 정보를 업데이트 하세요. 휴대폰 번호를 재등록 하지 않으면 비밀번호 찾기를 할 수 없습니다."
                         btnOKLabel:@"지금"
                     btnCancelLabel:@"나중에"
                         completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                             
                             if (buttonIndex == 0) {
                                 
                                 SettingsNumChangeViewController *vc = (SettingsNumChangeViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"SettingsNumChangeViewController" storyboardName:@"Settings"];
                                 vc.isPresente = YES;
                                 vc.moveToMain = YES;
                                 [self presentViewController:vc animated:YES completion:nil];
                                 
                             }
                             else{
                                 
                                  [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 *message1 = [NSString stringWithFormat:@"%@에서\n인증 메일을 확인하세요", [JDFacade facade].tmpEmailId];
    NSString *message2 = @"\n\n메일을 확인할 수 없는 경우에는\n스팸 메일함을 확인해보세요";
    CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"메일을 확인하세요" message:[NSString stringWithFormat:@"%@%@", message1, message2] delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
    [alert.lblMessage1 setColor:kUITextColor02 text:message1];
    
    [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 setRootViewController:vc];
}

- (void)requestLogout {
    
    [JDFacade facade].loginUser = nil;
    [self actionAfterLogout];
//    NSDictionary *param = @{API_AUTHORIZATION_KEY: [[JDFacade facade].loginUser authorization],
//                            @"message_type": @"auth.out"};
//    
//    [self sendDataToSocket:param];
    
    //parameters
//    [self actionAfterLogout];
//    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] storeObjectToUserDefaults:@(YES) forKey:USDEF_POPUP_MASTER];
    [[JDFacade facade] storeObjectToUserDefaults:@(YES) forKey:USDEF_POPUP_UPDATE];
    
    if (![[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_SAVE_ID] boolValue]) {

        [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID];
    }

    [JDFacade facade].loginUser = nil;

    [self closeSocket];

    [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
    
    //root view 변경
    [[JDFacade facade].appDelegate.window setRootViewController:self];

}

#pragma mark - UI Events
- (IBAction)btnLogInTouched:(id)sender {
    
//#ifdef DEBUG_MODE
//    if ([_txtEmail.text isEmptyString]) {
//        _txtEmail.text = @"asura77";//@"smiles1080";
//    }
//
//    if ([_txtPasswd.text isEmptyString]) {
//        _txtPasswd.text = @"12345678a";//@"12341234aa";
//
//    }
//#endif

    // TODO : 아이디 형식 검사할것
//    if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeEmail title:@"이메일" ]) {
//        return;
//    }

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

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

    [self requestLogin];
}


//회원가입 호출
- (void)lblSignUpTouched {

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

    UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:vc];
    
    [self presentViewController:m_navi animated:YES completion:nil];
    
}

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

// 아이디 찾기 호출
- (IBAction)btnIdFindTouched:(id)sender {
    NSLog(@"아이디 찾기");
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"IdFindViewController" storyboardName:@"SignUp"];
    
    
    UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:vc];
    
    [self presentViewController:m_navi animated:YES completion:nil];
}

// 비밀번호 찾기 호출
- (IBAction)btnPwFindTouched:(id)sender {
    NSLog(@"비밀번호 찾기");
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"PwFindViewController" storyboardName:@"SignUp"];
    
    
    UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:vc];
    
    [self presentViewController:m_navi animated:YES completion:nil];
}


#pragma mark - CustomTextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if ([textField isEqual:_txtEmail])
    {
        [_txtPasswd becomeFirstResponder];
    }
    
    if ([textField isEqual:_txtPasswd])
    {
        [self btnLogInTouched:nil];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    NSString *userID = [textField isEqual:_txtEmail] ? text : _txtEmail.text;
    NSString *userPW = [textField isEqual:_txtPasswd] ? text : _txtPasswd.text;
    
    _btnLogin.enabled = userID.length >= 6 && userPW.length >= 8;
    
    return YES;
}

//다음
- (void)moveToNextField:(id)sender {

    [_txtPasswd becomeFirstResponder] ;
    
}


#pragma mark - SocketService
- (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result
{
    SWITCH(result.messageType)
    {
        
        CASE (MSG_TYPE_LOGIN)
        {
            [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
            
            if (result.isSuccess) {
                LoginModel *loginInfo = (LoginModel *)message;
                [self actionForLoginSucceed:loginInfo];
            }
            else {
                
                [self loginErrorAlert:result];
            }
            
            break;
        }
        CASE (MSG_TYPE_AUTO_LOGIN)
        {
            [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
            if (result.isSuccess) {
                
                LoginModel *loginInfo = (LoginModel *)message;
                loginInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
                loginInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
                [self actionForLoginSucceed:loginInfo];
            }
            else {
                
                [self loginErrorAlert:result];
            }
            
            break;
        }
        CASE(@"auth.out")
        {
            if (result.isSuccess) {
                [self actionAfterLogout];
            }
            else {
                NSLog(@"Result Info : %@", result);
            }
                
        }
        DEFAULT
        {
            break;
        }
    }
}


- (void) loginErrorAlert:(SocketModel*)result {

    if (EQUALS(result.resultCode, @"102")) {

        [[JDFacade facade] confirmTitle:@"로그인 오류" message:@"로그인이 제한됩니다. 비밀번호 찾기 후 로그인 하세요." btnOKLabel:@"지금" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            
            if (buttonIndex == 0) {
             
                [self btnPwFindTouched:nil];
            }
            
        }];
    }
    else {
        
        [[JDFacade facade] alertTitle:@"알림" message:result.resultMsg];
    }
}

- (void) socketDidFailWithError:(NSError *)error {
    [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
}



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


@end
