//
// ChangePasswordViewController.m
// Project
//
// Created by ziv on 2017/6/12.
//
//

#import "ChangePasswordViewController.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "WebService.h"
#import "Vars.h"

@interface ChangePasswordViewController ()
@property (nonatomic, strong) NSArray *cellDataArray;
@property (nonatomic, assign) BOOL isLogin;
@property (nonatomic, strong) NSString *currentPassword;
@property (nonatomic, strong) NSString *theNewPassword;
@property (nonatomic, strong) NSString *confirmPassword;
@end

@implementation ChangePasswordViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.isLogin = YES;
	@weakify(self)
	if (YES) {
		UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultSegmentedControlHeight] + 15 * 2)];
		UISegmentedControl *segmentController = [[UISegmentedControl alloc] initWithItems:@[IMLocalizedString(@"Log in"), IMLocalizedString(@"Execution")]];
		segmentController.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultSegmentedControlHeight]);
		segmentController.selectedSegmentIndex = 0;
		[segmentController bk_addEventHandler:^(UISegmentedControl *segment) {
			@strongify(self)
			self.isLogin = segment.selectedSegmentIndex == 0;
		} forControlEvents:UIControlEventValueChanged];
		[headerView addSubview:segmentController];
		self.tableView.tableHeaderView = headerView;
	}
	if (YES) {
		UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight] + 15 * 2)];
		UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
		button.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]);
		button.backgroundColor = [Vars defaultTintColor];
		button.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
		[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[button setTitle:IMLocalizedString(@"Save") forState:UIControlStateNormal];
		[button bk_addEventHandler:^(id sender) {
			@strongify(self)
			if ([self validateChangePassword]) {
				[self changePassword];
			}
		} forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:button];
		[footerView addSubview:button];
		self.tableView.tableFooterView = footerView;
	}
	[self buildCellDataSource];
}

#pragma mark - Network

- (void)changePassword {
	ChangePassword *changePassword = [[ChangePassword alloc] init];
	changePassword.isLogin = self.isLogin;
	changePassword.oldPassword = self.currentPassword;
	changePassword.newPassword = self.theNewPassword;
	changePassword.newPasswordConfirm = self.confirmPassword;

	NSDictionary *requestDict = [Utility perlParamXml:[changePassword innerXML] action:changePassword.name];

	[Utility getXMLFromRequestWithMethod:@"GET" url:changePassword.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		// NSLog(@"%@", jsonDict);
		if (![mapper parseWithJSONObject:jsonDict]) {
			WebServiceResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				[self.navigationController popViewControllerAnimated:YES];
			}
		}
	}];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.editingType = TableViewCellEditingTypeTextField;
		data.showsRequiredAsteriskDuringEditing = YES;
		data.allowsPlaceholderFloating = YES;
		data.placeholder = IMLocalizedString(@"Current Password");
		data.observedObject = self;
		data.keyPath = @"currentPassword";
		[data addIntegrityValidationRuleBlock:^BOOL {
			@strongify(self)
			return [Utility canBeConvertedToUrlEncodedFromString:self.currentPassword];
		} withMessageBlock:^NSString * {
			return IMLocalizedString(@"Please enter alphabetic characters only");
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.editingType = TableViewCellEditingTypeTextField;
		data.showsRequiredAsteriskDuringEditing = YES;
		data.secureTextEntry = YES;
		data.placeholder = IMLocalizedString(@"New Password");
		data.allowsPlaceholderFloating = YES;
		data.observedObject = self;
		data.keyPath = @"theNewPassword";
		[data addIntegrityValidationRuleBlock:^BOOL {
			@strongify(self)
			return [Utility canBeConvertedToUrlEncodedFromString:self.theNewPassword];
		} withMessageBlock:^NSString * {
			return IMLocalizedString(@"Please enter alphabetic characters only");
		}];
		[data addIntegrityValidationRuleBlock:^BOOL {
			@strongify(self)
			return ![self.theNewPassword isEqualToString:self.currentPassword];
		} withMessageBlock:^NSString * {
			return IMLocalizedString(@"New password should be different from the old one");
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.editingType = TableViewCellEditingTypeTextField;
		data.showsRequiredAsteriskDuringEditing = YES;
		data.secureTextEntry = YES;
		data.placeholder = IMLocalizedString(@"Confirm New Password");
		data.allowsPlaceholderFloating = YES;
		data.observedObject = self;
		data.keyPath = @"confirmPassword";
		[data addIntegrityValidationRuleBlock:^BOOL {
			@strongify(self)
			return [Utility canBeConvertedToUrlEncodedFromString:self.confirmPassword];
		} withMessageBlock:^NSString * {
			return IMLocalizedString(@"Please enter alphabetic characters only");
		}];
		[data addIntegrityValidationRuleBlock:^BOOL {
			@strongify(self)
			return [self.confirmPassword isEqualToString:self.theNewPassword];
		} withMessageBlock:^NSString * {
			return IMLocalizedString(@"Two passwords are not identical");
		}];
		[array addObject:data];
	}
	self.cellDataArray = array;
}

- (BOOL)validateChangePassword {
	[self.tableView endEditing:YES];
	for (int row = 0; row < self.cellDataArray.count; row++) {
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
		TableViewCellData *data = self.cellDataArray[indexPath.row];
		if (![data validateRequired]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[data requiredValidationMessage:NO] dismissalHandler:^{
				[UIToolkit tableView:self.tableView atIndexPath:indexPath didFocusWithData:data];
			}];
			return NO;
		}
		if (![data validateIntegrity]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[data integrityValidationMessage:NO] dismissalHandler:^{
				[UIToolkit tableView:self.tableView atIndexPath:indexPath didFocusWithData:data];
			}];
			return NO;
		}
	}
	return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.cellDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
