#import "MailViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "PerlWS.h"
#import "Vars.h"

@interface MailViewController ()

@property (weak, nonatomic) IBOutlet UITextField *subjectTextField;
@property (weak, nonatomic) IBOutlet UITextView *messageBodyTextView;

- (IBAction)updateTitle:(id)sender;

@end

@implementation MailViewController

static NSString *defaultTitlePlaceholder;

+ (void)initialize {
	defaultTitlePlaceholder = IMLocalizedString(@"New Message");
}

- (instancetype)init {
	if (self = [super init]) {
		self.edgesForExtendedLayout = UIRectEdgeNone;
		// Custom initialization
		self.title = defaultTitlePlaceholder;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];

	if (@available(iOS 11.0, *)) {
		self.messageBodyTextView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
	} else {
		self.automaticallyAdjustsScrollViewInsets = NO;
	}

	@weakify(self)
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] im_initWithBarButtonSystemItem:UIBarButtonSystemItemCancel handler:^(UIBarButtonItem *barButtonItem) {
		@strongify(self)
		[self.navigationController popViewControllerAnimated: YES];
	}];
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] im_initWithTitle:IMLocalizedString(@"Send") style:UIBarButtonItemStylePlain handler:^(UIBarButtonItem *barButtonItem) {
		@strongify(self)
		if ([self validateRequest]) {
			[self addRequest];
		}
	}];
}

- (void)viewDidLayoutSubviews {
	[super viewDidLayoutSubviews];

	[DrawUtils addBorderToRect:self.messageBodyTextView byEdges:UIRectEdgeTop strokeColor:[UIColor lightGrayColor]];
}

#pragma mark - Action

- (IBAction)updateTitle:(id)sender {
	if ([StringUtils isBlank:self.subjectTextField.text]) {
		self.navigationItem.title = defaultTitlePlaceholder;
		self.navigationItem.rightBarButtonItem.style = UIBarButtonItemStylePlain;
	} else {
		self.navigationItem.title = self.subjectTextField.text;
		self.navigationItem.rightBarButtonItem.style = UIBarButtonItemStyleDone;
	}
}

#pragma mark - Network

- (void)addRequest {
	AddRequest *addRequest = [[AddRequest alloc] init];
	addRequest.subject = self.subjectTextField.text;
	addRequest.message = self.messageBodyTextView.text;

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

	[Utility getXMLFromRequestWithMethod:@"POST" url:addRequest.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[AddRequestResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			AddRequestResponse *response = mapper.response;
			if (![StringUtils isEmpty:response.error]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error];
			} else {
				if (response.status == 1) {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Sent successfully") dismissalHandler:^{
						[self.navigationController popViewControllerAnimated:YES];
					}];
				} else {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:IMLocalizedString(@"Sent failed") dismissalHandler:^{
						[self.navigationController popViewControllerAnimated:YES];
					}];
				}
			}
		}
	}];
}

#pragma mark - Private

- (BOOL)validateRequest {
	[self.view endEditing:YES];
	if ([StringUtils isBlank:self.subjectTextField.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please fill out subject") dismissalHandler:^{
			[self.subjectTextField becomeFirstResponder];
		}];
		return NO;
	}
	if ([StringUtils isBlank:self.messageBodyTextView.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please fill out message") dismissalHandler:^{
			[self.messageBodyTextView becomeFirstResponder];
		}];
		return NO;
	}
	if (![Utility canBeConvertedToUrlEncodedFromString:self.subjectTextField.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
			[self.subjectTextField becomeFirstResponder];
		}];
		return NO;
	}
	if (![Utility canBeConvertedToUrlEncodedFromString:self.messageBodyTextView.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
			[self.messageBodyTextView becomeFirstResponder];
		}];
	}
	return YES;
}

@end
