//
// JoinViewController.m
// GoToBus
//
// Created by paul on 8/13/14.
//
//

#import "JoinViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "AnswersManager.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ComboBoxViewController.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/A2DynamicDelegate.h>
#import <BlocksKit/NSObject+A2DynamicDelegate.h>
#import "Utility.h"
#import "Address.h"
#import "User.h"
#import "CustomDualTextFieldView.h"
#import "CustomTextFieldView.h"
#import "ContactsManager.h"
#import "PerlWS.h"
#import "RegistrationResponseJsonMapper.h"
#import "Vars.h"

@interface JoinViewController ()

@property (nonatomic, weak) IBOutlet CustomTextFieldView *emailView;
@property (nonatomic, weak) IBOutlet CustomTextFieldView *pwdView;
@property (nonatomic, weak) IBOutlet CustomTextFieldView *retypePwdView;
@property (nonatomic, weak) IBOutlet CustomDualTextFieldView *nameView;
@property (nonatomic, weak) IBOutlet UIButton *registerButton;
@property (nonatomic, weak) IBOutlet UIButton *rememberTravelButton;
@property (weak, nonatomic) IBOutlet UIStackView *buttonStackView;

@property (nonatomic, strong) id segueObject;
@property (nonatomic, assign) BOOL popAnimated;
@property (nonatomic, copy) void (^destructiveBlock) (void);

@property (nonatomic, strong, readonly) UITextField *emailField;
@property (nonatomic, strong, readonly) UITextField *passwordField;
@property (nonatomic, strong, readonly) UITextField *repasswordField;
@property (nonatomic, strong, readonly) UITextField *firstNameField;
@property (nonatomic, strong, readonly) UITextField *lastNameField;

- (IBAction)registerAccount:(id)sender;
- (IBAction)toggleTravelRemember:(id)sender;

@end

@implementation JoinViewController

- (instancetype)init {
	self = [super init];
	if (self) {
		// Custom initialization
		self.title = IMLocalizedString(@"Register");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

    self.emailView.asteriskLabel.hidden = YES;
	self.emailField.placeholder = IMLocalizedString(@"Email Address");
	self.emailField.im_textContentType = IMTextContentTypeEmailAddress;
	self.emailField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.emailField.autocorrectionType = UITextAutocorrectionTypeNo;
	self.emailField.keyboardType = UIKeyboardTypeEmailAddress;
	[CocoaUtils addKeyboardToolbarForTextField:self.emailField title:IMLocalizedString(@"Open Contacts") handler:^{
		[CocoaUtils showSelectionOfContactWithDisplayedPropertyKeys:@[CMContactEmailAddressesKey] completion:^(CMContactProperty *contactOrProperty) {
			self.emailField.text = contactOrProperty.value;
		}];
	}];

    self.pwdView.asteriskLabel.hidden = YES;
	self.passwordField.placeholder = IMLocalizedString(@"Password");
	self.passwordField.im_textContentType = IMTextContentTypePassword;
	self.passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.passwordField.autocorrectionType = UITextAutocorrectionTypeNo;
	self.passwordField.secureTextEntry = YES;
	self.passwordField.clearsOnBeginEditing = YES;

    self.retypePwdView.asteriskLabel.hidden = YES;
	self.repasswordField.placeholder = IMLocalizedString(@"Re-type Password");
	self.repasswordField.im_textContentType = IMTextContentTypePassword;
	self.repasswordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.repasswordField.autocorrectionType = UITextAutocorrectionTypeNo;
	self.repasswordField.secureTextEntry = YES;
	self.repasswordField.clearsOnBeginEditing = YES;

    self.nameView.imageView.hidden = YES;
	self.firstNameField.placeholder = IMLocalizedString(@"First Name");
	self.firstNameField.im_textContentType = IMTextContentTypeGivenName;
	self.firstNameField.autocapitalizationType = UITextAutocapitalizationTypeWords;
	[CocoaUtils addKeyboardToolbarForTextField:self.firstNameField title:IMLocalizedString(@"Open Contacts") handler:^{
		[CocoaUtils showSelectionOfContactWithDisplayedPropertyKeys:@[CMContactGivenNameKey, CMContactFamilyNameKey] completion:^(CMContact *contact) {
			self.firstNameField.text = contact.givenName;
			self.lastNameField.text = contact.familyName;
		}];
	}];

	self.lastNameField.placeholder = IMLocalizedString(@"Last Name");
	self.lastNameField.im_textContentType = IMTextContentTypeFamilyName;
	self.lastNameField.autocapitalizationType = UITextAutocapitalizationTypeWords;
	[CocoaUtils addKeyboardToolbarForTextField:self.lastNameField title:IMLocalizedString(@"Open Contacts") handler:^{
		[CocoaUtils showSelectionOfContactWithDisplayedPropertyKeys:@[CMContactGivenNameKey, CMContactFamilyNameKey] completion:^(CMContact *contact) {
			self.firstNameField.text = contact.givenName;
			self.lastNameField.text = contact.familyName;
		}];
	}];

	[self.rememberTravelButton setTitle:IMLocalizedString(@"Travel Deals Newsletter") forState:UIControlStateNormal];
    [self.rememberTravelButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
    [self.rememberTravelButton setImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesomeRegular squareIconWithSize:CGRectGetHeight(self.rememberTravelButton.frame)] fillColor:[Vars defaultTintColor]] forState:UIControlStateNormal];
    [self.rememberTravelButton setImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesomeRegular checkSquareIconWithSize:CGRectGetHeight(self.rememberTravelButton.frame)] fillColor:[Vars defaultTintColor]] forState:UIControlStateSelected];
    
	self.registerButton.backgroundColor = [Vars defaultTintColor];
	[self.registerButton setTitle:IMLocalizedString(@"Create Account") forState:UIControlStateNormal];
	[Utility addRoundedBorderToButton:self.registerButton];
    
    UIButton *signUpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    NSMutableAttributedString *signUpAttributedString = [[NSMutableAttributedString alloc] init];
	[signUpAttributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"Already registered?") attributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]}] ];
	[signUpAttributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
	[signUpAttributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"Login") attributes:@{NSForegroundColorAttributeName:[Vars defaultTintColor]}]];
    [signUpButton setAttributedTitle:signUpAttributedString forState:UIControlStateNormal];
    [signUpButton addTarget:self action:@selector(performActionForLoginBack) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonStackView addArrangedSubview:signUpButton];
}

#pragma mark - Public

- (void)performSegueWithObject:(id)object popAnimated:(BOOL)animated {
	self.segueObject = object;
	self.popAnimated = animated;
}

#pragma mark - Property

- (UITextField *)emailField {
	return self.emailView.textField;
}

- (UITextField *)passwordField {
	return self.pwdView.textField;
}

- (UITextField *)repasswordField {
	return self.retypePwdView.textField;
}

- (UITextField *)firstNameField {
	return self.nameView.leftTextField;
}

- (UITextField *)lastNameField {
	return self.nameView.rightTextField;
}

#pragma mark - Action

-(void)performActionForLoginBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)toggleTravelRemember:(id)sender {
	self.rememberTravelButton.selected = !self.rememberTravelButton.selected;
}

- (IBAction)registerAccount:(id)sender {
	if ([self validateRegistration]) {
		[self registration];
	}
}

#pragma mark - Network

- (void)registration {
	Registration *registration = [[Registration alloc] init];
	registration.email = self.emailField.text;
	registration.password = self.passwordField.text;
	registration.firstName = self.firstNameField.text;
	registration.lastName = self.lastNameField.text;
	registration.subscription = self.rememberTravelButton.selected;

	NSDictionary *requestDict = [Utility perlParamXml:[registration innerXML] action:registration.name];
	// NSLog(@"%@", requestDict);
	[Utility getXMLFromRequestWithMethod:@"GET" url:registration.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		RegistrationResponseJsonMapper *mapper = [[RegistrationResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		NSError *parseError = [mapper parseWithJSONObject:jsonDict];
		if (!parseError) {
			RegistrationResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else if ([StringUtils isEmpty:response.user.cookie_string]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:[Vars responseException]];
			} else {
				User *user = response.user;
				user.pass1 = registration.password;
				[Vars appDelegate].loginUser = user;

				NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
				[userDefaults setInteger:[Vars appDelegate].loginUser.id forKey:UserDefaultsKeyUserID];
				[userDefaults setObject:[Vars appDelegate].loginUser.uid forKey:UserDefaultsKeyUserName];
				[userDefaults setObject:[Vars appDelegate].loginUser.pass1 forKey:UserDefaultsKeyUserPassword];

				NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
				[notificationCenter postNotificationName:SegueDidPerformNotification object:self.segueObject];
				[notificationCenter postNotificationName:LoginStatusDidChangeNotification object:nil];

				[AnswersManager logSignUp];
				[AnswersManager logLoginWithMethod:@"Password" success:YES];

				[CocoaUtils popViewControllerInQuantity:2 onNavigationController:self.navigationController animated:self.popAnimated];

				if (self.destructiveBlock) {
					self.destructiveBlock();
				}
			}
		}
	}];
}

#pragma mark - Private

- (BOOL)validateRegistration {
	[self.scrollView endEditing:YES];
	for (UITextField *textField in @[self.emailField, self.passwordField, self.repasswordField]) {
		if ([StringUtils isBlank:textField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), textField.placeholder.lowercaseString] dismissalHandler:^{
				[textField becomeFirstResponder];
			}];
			return NO;
		}
	}
	for (UITextField *textField in @[self.emailField, self.firstNameField, self.lastNameField]) {
		if (![Utility canBeConvertedToUrlEncodedFromString:textField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
				[textField becomeFirstResponder];
			}];
			return NO;
		}
	}
	if (![self.passwordField.text isEqualToString:self.repasswordField.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Two passwords are not identical")];
		return NO;
	}
	return YES;
}

#pragma mark

- (void)dealloc {
	[[Vars appDelegate] dashboard];
}

@end
