//
//  LoginViewController.m
//  LifeLog
//
//  Created by Nguyen Van Phong on 7/30/17.
//  Copyright © 2017 PhongNV. All rights reserved.
//

#import "LoginViewController.h"
#import "ServerAPI.h"
#import "AppDelegate.h"
#import "RegisterViewController.h"
#import "Utilities.h"
#import "ConfirmForgetPassViewController.h"

@interface LoginViewController ()
@property (nonatomic, weak) IBOutlet UILabel *lblEmail;
@property (nonatomic, weak) IBOutlet UILabel *lblPassword;
@property (nonatomic, weak) IBOutlet UILabel *lblRegister;
@property (nonatomic, weak) IBOutlet UITextField *tfEmail;
@property (nonatomic, weak) IBOutlet UITextField *tfPassword;
@property (nonatomic, weak) IBOutlet UIButton *btnLogin;
@property (nonatomic, weak) IBOutlet UIButton *btnRegist;
@property (nonatomic, weak) IBOutlet UIButton *btnForget;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = NSLocalizedString(@"lifelog.login.title", nil);
  
    self.lblEmail.text = NSLocalizedString(@"lifelog.common.email", nil);
    self.lblPassword.text = NSLocalizedString(@"lifelog.common.password", nil);
    self.lblRegister.text = NSLocalizedString(@"lifelog.login.label.register", nil);
  
    [self.btnLogin setTitle:NSLocalizedString(@"lifelog.login.button.login", nil) forState:UIControlStateNormal];
    [self.btnRegist setTitle:NSLocalizedString(@"lifelog.login.button.register", nil) forState:UIControlStateNormal];
  
    NSMutableAttributedString *forgetString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"lifelog.login.forget.password", nil)];
    [forgetString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [forgetString length])];
    // Or for adding Colored text use----------
    UIColor* textColor = [UIColor blueColor];
    [forgetString setAttributes:@{NSForegroundColorAttributeName:textColor,NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(0,[forgetString length])];
    // Or for adding Colored text use----------
    [_btnForget setAttributedTitle:forgetString forState:UIControlStateNormal];
  
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"lifelog.common.back", nil) style:UIBarButtonItemStylePlain target:nil action:nil];
}

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

- (BOOL)checkAllowLogin
{
    NSString *message = @"";
    if (_tfEmail.text.length <= 0) {
        message = @"Please input email";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfPassword.text.length <= 0) {
        message = @"Please input password";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfEmail.text.length > 255) {
        message = @"Email maximum length 255";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfPassword.text.length < 6) {
        message = @"Password minimum length 6";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (![_tfEmail.text containsString:@"@"]) {
        message = @"Email invalid";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    return YES;
}

- (IBAction)buttonLoginTouchUpInside:(id)sender {
    [self resignTextField];
    if (![self checkAllowLogin]) {
        return;
    }
    LoginViewController __weak *weakSelf = self;
    [[ServerAPI server] loginWithEmail:_tfEmail.text Password:_tfPassword.text CompletionHandler:^(User *user, NSString *token, NSError *error) {
        if (error == nil) {
            // save user and goto MainMenu
            // For Saving
            NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:user];
            [[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:kUser];
            [[NSUserDefaults standardUserDefaults] setObject:token forKey:kToken];
            [[NSUserDefaults standardUserDefaults] synchronize];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[AppDelegate sharedAppDelegate] gotoMainMenu];
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *message = [error.userInfo objectForKey:@"message"];
                [Utilities showErrorMessage:message withViewController:weakSelf];
          });
        }
    }];
}

- (IBAction)buttonForgetTouchUpInside:(id)sender {
    [self resignTextField];
    if (_tfEmail.text.length > 0) {
        LoginViewController __weak *weakSelf = self;
        [[ServerAPI server] forgetPass:_tfEmail.text CompletionHandler:^(NSError *error) {
            if (error == nil) {
                // goto screen confirm forgetPass
                dispatch_async(dispatch_get_main_queue(), ^{
                    ConfirmForgetPassViewController *confirmVC = [[ConfirmForgetPassViewController alloc] initWithNibName:@"ConfirmForgetPassViewController" bundle:nil];
                    confirmVC.email = weakSelf.tfEmail.text;
                    [weakSelf.navigationController pushViewController:confirmVC animated:YES];
                });
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *message = [error.userInfo objectForKey:@"message"];
                    [Utilities showErrorMessage:message withViewController:weakSelf];
                });
            }
        }];
    }
    else {
        [Utilities showErrorMessage:@"Please input email" withViewController:self];
    }
}

- (IBAction)buttonRegisterTouchUpInside:(id)sender {
    [self resignTextField];
    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (void)resignTextField
{
    [_tfEmail resignFirstResponder];
    [_tfPassword resignFirstResponder];
}

@end
